The query below works only when searching for dependencies on a table and not those on a column:
EXEC sp_depends @objname = N'TableName';
However, the following query is the best option if you want to search for all sorts of dependencies, it does not miss any thing. It actually gives more information than required.
select distinct
so.name
--, text
from
sysobjects so,
syscomments sc
where
so.id = sc.id
and lower(text) like '%organizationtypeid%'
order by so.name
Yes, you can apply CSS to SVG, but you need to match the element, just as when styling HTML. If you just want to apply it to all SVG paths, you could use, for example:
?path {
fill: blue;
}?
External CSS appears to override the path's fill
attribute, at least in WebKit and Gecko-based browsers I tested. Of course, if you write, say, <path style="fill: green">
then that will override external CSS as well.
Open Sublime Text console ? paste in opened field:
sublime.packages_path()
? Enter. You get result in console output.
This answer is relevant for April 2018. In the future, the data of this answer may be obsolete.
I'm not recommended @osiris answer. Arguments:
Packages
folder.One solution would be to divide your table into 20 columns of 5% width each, then use colspan on each real column to get the desired width, like this:
<html>_x000D_
<body bgcolor="#14B3D9">_x000D_
<table width="100%" border="1" bgcolor="#ffffff">_x000D_
<colgroup>_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
</colgroup>_x000D_
<tr>_x000D_
<td colspan=5>25</td>_x000D_
<td colspan=10>50</td>_x000D_
<td colspan=5>25</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan=10>50</td>_x000D_
<td colspan=6>30</td>_x000D_
<td colspan=4>20</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
Here is an updated version for Chart.js 2.3
Sep 23, 2016: Edited my code to work with v2.3 for both line/bar type.
Important: Even if you don't need the animation, don't change the duration option to 0, otherwise you will get chartInstance.controller is undefined error.
var chartData = {_x000D_
labels: ["January", "February", "March", "April", "May", "June"],_x000D_
datasets: [_x000D_
{_x000D_
fillColor: "#79D1CF",_x000D_
strokeColor: "#79D1CF",_x000D_
data: [60, 80, 81, 56, 55, 40]_x000D_
}_x000D_
]_x000D_
};_x000D_
_x000D_
var opt = {_x000D_
events: false,_x000D_
tooltips: {_x000D_
enabled: false_x000D_
},_x000D_
hover: {_x000D_
animationDuration: 0_x000D_
},_x000D_
animation: {_x000D_
duration: 1,_x000D_
onComplete: function () {_x000D_
var chartInstance = this.chart,_x000D_
ctx = chartInstance.ctx;_x000D_
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);_x000D_
ctx.textAlign = 'center';_x000D_
ctx.textBaseline = 'bottom';_x000D_
_x000D_
this.data.datasets.forEach(function (dataset, i) {_x000D_
var meta = chartInstance.controller.getDatasetMeta(i);_x000D_
meta.data.forEach(function (bar, index) {_x000D_
var data = dataset.data[index]; _x000D_
ctx.fillText(data, bar._model.x, bar._model.y - 5);_x000D_
});_x000D_
});_x000D_
}_x000D_
}_x000D_
};_x000D_
var ctx = document.getElementById("Chart1"),_x000D_
myLineChart = new Chart(ctx, {_x000D_
type: 'bar',_x000D_
data: chartData,_x000D_
options: opt_x000D_
});
_x000D_
<canvas id="myChart1" height="300" width="500"></canvas>
_x000D_
Somtimes things aren't always as they seem when in comes to config files in general. So here I'm applying my usual methods for exploring what files are opened by a process.
I use a very powerful and useful command-line program called strace to show me what's really going on behind my back!
$ strace -o strace.log php --version
$ grep php.ini strace.log
Strace digs out kernel (system) calls that your program makes and dumps the output into the file specified by -o
It's easy to use grep to search for occurrences of php.ini in this log. It's pretty obvious looking at the following typical response to see what is going on.
open("/usr/bin/php.ini", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/etc/php.ini", O_RDONLY) = 3
lstat("/etc/php.ini", {st_mode=S_IFREG|0644, st_size=69105, ...}) = 0
If you're trying to get XAMPP to use a network drive as your document root you have to use UNC paths in httpd.conf. XAMPP will not recognize your mapped network drives.
For example the following won't work, DocumentRoot "X:/webroot"
But this will, DocumentRoot "//192.168.10.100/webroot" (note the forward slashes, not back slashes)
Building on mightybyte's answer for those who aren't comfortable with *nix shell scripting, here's a working script:
#!/bin/sh
PGPASSFILE=/tmp/pgpasswd$$
touch $PGPASSFILE
chmod 600 $PGPASSFILE
echo "myserver:5432:mydb:jdoe:password" > $PGPASSFILE
export PGPASSFILE
psql mydb
rm $PGPASSFILE
The double dollar sign ($$
) in /tmp/pgpasswd$$
at line 2 appends the process ID number to the file name, so that this script can be run more than once, even simultaneously, without side effects.
Note the use of the chmod
command at line 4 - just like the "not a plain file" error that mightybyte described, there's also a "permissions" error if this is not done.
At line 7, you won't have to use the -h
myserver, the -p
myport, or -U
jdoe flag if you use the defaults (localhost : 5432) and only have one database user. For multiple users, (but the default connection) change that line to
psql mydb jdoe
Don't forget to make the script executable with
chmod +x runpsql
(or whatever you called the script file)
UPDATE:
I took RichVel's advice and made the file unreadable before putting the password into it. That closes a slight security hole. Thanks!
Below is Example of simple dropdown using jstl tag
<form:select path="cityFrom">
<form:option value="Ghaziabad" label="Ghaziabad"/>
<form:option value="Modinagar" label="Modinagar"/>
<form:option value="Meerut" label="Meerut"/>
<form:option value="Amristar" label="Amristar"/>
</form:select>
For newer versions of Angular:
-write it as [(ngModel)] = yourSearch
declare a empty variable(property) named as yourSearch
in .ts
file
add FormsModule
in app.module.ts
file from - @angular/forms;
if your application is running, then restart it as you made changes in its module.ts
file
Your bean or pojo class should implements parcelable interface
.
For example:
public class BeanClass implements Parcelable{
String name;
int age;
String sex;
public BeanClass(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public static final Creator<BeanClass> CREATOR = new Creator<BeanClass>() {
@Override
public BeanClass createFromParcel(Parcel in) {
return new BeanClass(in);
}
@Override
public BeanClass[] newArray(int size) {
return new BeanClass[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
dest.writeString(sex);
}
}
Consider a scenario that you want to send the arraylist
of beanclass
type from Activity1
to Activity2
.
Use the following code
Activity1:
ArrayList<BeanClass> list=new ArrayList<BeanClass>();
private ArrayList<BeanClass> getList() {
for(int i=0;i<5;i++) {
list.add(new BeanClass("xyz", 25, "M"));
}
return list;
}
private void gotoNextActivity() {
Intent intent=new Intent(this,Activity2.class);
/* Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)list);
intent.putExtra("BUNDLE",args);*/
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("StudentDetails", list);
intent.putExtras(bundle);
startActivity(intent);
}
Activity2:
ArrayList<BeanClass> listFromActivity1=new ArrayList<>();
listFromActivity1=this.getIntent().getExtras().getParcelableArrayList("StudentDetails");
if (listFromActivity1 != null) {
Log.d("listis",""+listFromActivity1.toString());
}
I think this basic to understand the concept.
If you don't want to use SMO, for example because you need to be cross-platform, you can also use the ScriptSplitter class from SubText.
Here's the implementation in C# & VB.NET
Usage:
string strSQL = @"
SELECT * FROM INFORMATION_SCHEMA.columns
GO
SELECT * FROM INFORMATION_SCHEMA.views
";
foreach(string Script in new Subtext.Scripting.ScriptSplitter(strSQL ))
{
Console.WriteLine(Script);
}
If you have problems with multiline c-style comments, remove the comments with regex:
static string RemoveCstyleComments(string strInput)
{
string strPattern = @"/[*][\w\d\s]+[*]/";
//strPattern = @"/\*.*?\*/"; // Doesn't work
//strPattern = "/\\*.*?\\*/"; // Doesn't work
//strPattern = @"/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/ "; // Doesn't work
//strPattern = @"/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/ "; // Doesn't work
// http://stackoverflow.com/questions/462843/improving-fixing-a-regex-for-c-style-block-comments
strPattern = @"/\*(?>(?:(?>[^*]+)|\*(?!/))*)\*/"; // Works !
string strOutput = System.Text.RegularExpressions.Regex.Replace(strInput, strPattern, string.Empty, System.Text.RegularExpressions.RegexOptions.Multiline);
Console.WriteLine(strOutput);
return strOutput;
} // End Function RemoveCstyleComments
Removing single-line comments is here:
https://stackoverflow.com/questions/9842991/regex-to-remove-single-line-sql-comments
It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
You can define foreign key by:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
// This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.
If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation
Data annotation:
// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }
Fluent API:
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithMany(p => p.Childs)
.HasForeignKey(c => c.ParentId);
Other types of constraints can be enforced by data annotations and model validation.
Edit:
You will get an exception if you don't set ParentId
. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.
I've used it in real-time programming. We typically don't want to perform any dynamic allocation (or deallocation) after the system starts up, because there's no guarantee how long that is going to take.
What I can do is preallocate a large chunk of memory (large enough to hold any amount of whatever that the class may require). Then, once I figure out at runtime how to construct the things, placement new can be used to construct objects right where I want them. One situation I know I used it in was to help create a heterogeneous circular buffer.
It's certainly not for the faint of heart, but that's why they make the syntax for it kinda gnarly.
The performance difference between a switch
and if...else if...else
is small, they basically do the same work. One difference between them that may make a difference is that the expression to test is only evaluated once in a switch
while it's evaluated for each if
. If it's costly to evaluate the expression, doing it one time is of course faster than doing it a hundred times.
The difference in implementation of those commands (and all script in general) differs quite a bit between browsers. It's common to see rather big performance differences for the same code in different browsers.
As you can hardly performance test all code in all browsers, you should go for the code that fits best for what you are doing, and try to reduce the amount of work done rather than optimising how it's done.
fields() and fieldNames() both were not working for me. And I had to spend quite sometime to find a way to iterate over the keys. There are two ways by which it can be done.
One is by converting it into a map (takes up more space):
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> result = mapper.convertValue(jsonNode, Map.class);
for (String key : result.keySet())
{
if(key.equals(foo))
{
//code here
}
}
Another, by using a String iterator:
Iterator<String> it = jsonNode.getFieldNames();
while (it.hasNext())
{
String key = it.next();
if (key.equals(foo))
{
//code here
}
}
And if you need to do it on items that match a specific condition...
double total = myList.Where(item => item.Name == "Eggs").Sum(item => item.Amount);
Because the answer is no longer valid with a more stable version of angular, I am posting a newer solution.
PHP Page: session.php
if (!isset($_SESSION))
{
session_start();
}
$_SESSION['variable'] = "hello world";
$sessions = array();
$sessions['variable'] = $_SESSION['variable'];
header('Content-Type: application/json');
echo json_encode($sessions);
Send back only the session variables you want in Angular not all of them don't want to expose more than what is needed.
JS All Together
var app = angular.module('StarterApp', []);
app.controller("AppCtrl", ['$rootScope', 'Session', function($rootScope, Session) {
Session.then(function(response){
$rootScope.session = response;
});
}]);
app.factory('Session', function($http) {
return $http.get('/session.php').then(function(result) {
return result.data;
});
});
HTML
Inside your html you can reference your session
<html ng-app="StarterApp">
<body ng-controller="AppCtrl">
{{ session.variable }}
</body>
If HTML and use bootstrap they have a helper class.
<span class="text-nowrap">1-866-566-7233</span>
On Suse Linux 13.2, pip calls python3, but pip2 is available to use the older python version.
I'm not really sure what your question is, but to get the text of the li
element you can use:
$(this).text();
And to get the id
of an element you can use .attr('id');
. Once you have a reference to the element you want (e.g. $(this)
) you can perform any jQuery function on it.
see if you are placing the client section in the correct web.config file. SharePoint has around 6 to 7 config files. http://msdn.microsoft.com/en-us/library/office/ms460914(v=office.14).aspx (http://msdn.microsoft.com/en-us/library/office/ms460914%28v=office.14%29.aspx)
Post this you can simply try
ServiceClient client = new ServiceClient("ServiceSOAP");
Accordingly to W3C checked input's attribute can be absent/ommited or have "checked" as its value. This does not invalidate other values because there's no restriction to the browser implementation to allow values like "true", "on", "yes" and so on. To guarantee that you'll write a cross-browser checkbox/radio use checked="checked", as recommended by W3C.
disabled, readonly and ismap input's attributes go on the same way.
EDITED
empty is not a valid value for checked, disabled, readonly and ismap input's attributes, as warned by @Quentin
According google docs ,we should not use fitsSystemWindows attribute in app theme, it is intended to use in layout files. Using in themes can causes problem in toast messages .
Check Issue here & example of problem caused here
<item name="android:fitsSystemWindows">true</item>
Example of using correct way and which works fine with windowTranslucentStatus as well.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<include layout="@layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</include>
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="@color/white"
android:animateLayoutChanges="true"
app:headerLayout="@layout/navigation_drawer_header"
app:menu="@menu/navigation_drawer_menu" />
</android.support.v4.widget.DrawerLayout>
You can use hive string function CONCAT_WS( string delimiter, string str1, string str2...strn )
for ex:
hive -e 'select CONCAT_WS(',',cola,colb,colc...,coln) from Mytable' > /home/user/Mycsv.csv
Although this is not supported by all browsers, if you use capturing parentheses inside your regular expression then the captured input is spliced into the result.
If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. [reference)
So:
var stringArray = str.split(/(\s+)/);
^ ^
//
Output:
["my", " ", "car", " ", "is", " ", "red"]
This collapses consecutive spaces in the original input, but otherwise I can't think of any pitfalls.
private String message;
private ScreenManager s;
//Here is an example of code to add the keyListener() as suggested; modify
public void init(){
Window w = s.getFullScreenWindow();
w.addKeyListener(this);
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_F5)
message = "Pressed: " + KeyEvent.getKeyText(keyCode);
}
You can't use margin:auto;
on position:absolute;
elements, just remove it if you don't need it, however, if you do, you could use left:30%;
((100%-40%)/2) and media queries for the max and min values:
.container {
position: absolute;
top: 15px;
left: 30%;
z-index: 2;
width:40%;
height: 60px;
overflow: hidden;
background: #fff;
}
@media all and (min-width:960px) {
.container {
left: 50%;
margin-left:-480px;
width: 960px;
}
}
@media all and (max-width:600px) {
.container {
left: 50%;
margin-left:-300px;
width: 600px;
}
}
Floats and doubles are approximate. If you create a BigDecimal and pass a float into the constructor you see what the float actually equals:
groovy:000> new BigDecimal(1.0F)
===> 1
groovy:000> new BigDecimal(1.01F)
===> 1.0099999904632568359375
this probably isn't how you want to represent $1.01.
The problem is that the IEEE spec doesn't have a way to exactly represent all fractions, some of them end up as repeating fractions so you end up with approximation errors. Since accountants like things to come out exactly to the penny, and customers will be annoyed if they pay their bill and after the payment is processed they owe .01 and they get charged a fee or can't close their account, it's better to use exact types like decimal (in C#) or java.math.BigDecimal in Java.
It's not that the error isn't controllable if you round: see this article by Peter Lawrey. It's just easier not to have to round in the first place. Most applications that handle money don't call for a lot of math, the operations consist of adding things or allocating amounts to different buckets. Introducing floating point and rounding just complicates things.
if you remove the float: left
from the a
and add white-space: nowrap
to the outer div
#myWorkContent{
width:530px;
height:210px;
border: 13px solid #bed5cd;
overflow-x: scroll;
overflow-y: hidden;
white-space: nowrap;
}
#myWorkContent a {
display: inline;
}
this should work for any size or amount of images..
or even:
#myWorkContent a {
display: inline-block;
vertical-align: middle;
}
which would also vertically align images of different heights if required
When you want to convert your code to result( executable, library or whatever ), there is 2 steps:
1) compile
2) link
In first step compiler should now about some things like sizeof objects that used by you, prototype of functions and maybe inheritance. on the other hand linker want to find implementation of functions and global variables in your code.
Now when you use ClassTwo
in File1.cpp
compiler know nothing about it and don't know how much memory should allocate for it or for example witch members it have or is it a class and enum or even a typedef of int, so compilation will be failed by the compiler. adding File2.cpp
solve the problem of linker that look for implementation but the compiler is still unhappy, because it know nothing about your type.
So remember, in compile phase you always work with just one file( and of course files that included by that one file ) and in link phase you need multiple files that contain implementations. and since C/C++ are statically typed and they allow their identifier to work for many purposes( definition, typedef, enum class, ... ) so you should always identify you identifier to the compiler and then use it and as a rule compiler should always know size of your variable!!
Keep in mind that the Fusion API is unmanaged. The current reference for it is here: Development Guide > Unmanaged API Reference > Fusion
However, there is a managed method to add an assembly to GAC: System.EnterpriseServices.Internal.Publish.GacInstall And, if you need to register any Types: System.EnterpriseServices.Internal.Publish.RegisterAssembly
The reference for the publish class is here: .NET Framework Class Library > System.EnterpriseServices Namespaces > System.EnterpriseServices.Internal
However, these methods were designed for installing components that are required by a web service application such as ASP.NET or WCF. As a result they don't register the assemblies with Fusion; thus, they can be uninstalled by other applications, or using gacutil and cause your assembly to stop working. So, if you use them outside of a web server where an administrator is managing the GAC then be sure to add a reference to your application in SOFTWARE\Wow6432Node\Microsoft\Fusion\References (for 64-bit OS) or SOFTWARE\Microsoft\Fusion\References (for 32-bit OS) so that nobody can remove your support assemblies unless they uninstall your application.
The DateTimeFormatInfo class implements this interface, so it allows you to control the formatting of your DateTime strings.
You can do it even without the HTTP_PROXY environment variable. Try this sample:
import urllib2
proxy_support = urllib2.ProxyHandler({"http":"http://61.233.25.166:80"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
html = urllib2.urlopen("http://www.google.com").read()
print html
In your case it really seems that the proxy server is refusing the connection.
Something more to try:
import urllib2
#proxy = "61.233.25.166:80"
proxy = "YOUR_PROXY_GOES_HERE"
proxies = {"http":"http://%s" % proxy}
url = "http://www.google.com/search?q=test"
headers={'User-agent' : 'Mozilla/5.0'}
proxy_support = urllib2.ProxyHandler(proxies)
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
urllib2.install_opener(opener)
req = urllib2.Request(url, None, headers)
html = urllib2.urlopen(req).read()
print html
Edit 2014:
This seems to be a popular question / answer. However today I would use third party requests
module instead.
For one request just do:
import requests
r = requests.get("http://www.google.com",
proxies={"http": "http://61.233.25.166:80"})
print(r.text)
For multiple requests use Session
object so you do not have to add proxies
parameter in all your requests:
import requests
s = requests.Session()
s.proxies = {"http": "http://61.233.25.166:80"}
r = s.get("http://www.google.com")
print(r.text)
<input id='r1' type='radio' class='rg' name="asdf"/>
<input id='r2' type='radio' class='rg' name="asdf"/>
<input id='r3' type='radio' class='rg' name="asdf"/>
<input id='r4' type='radio' class='rg' name="asdf"/><br/>
<input type='text' id='r1edit'/>
jquery part
$(".rg").change(function () {
if ($("#r1").attr("checked")) {
$('#r1edit:input').removeAttr('disabled');
}
else {
$('#r1edit:input').attr('disabled', 'disabled');
}
});
here is the DEMO
I believe simply img.shape[-1::-1]
would be nicer.
It's not that above answers are incorrect, but I find this code extremely easy to understand and therefore I am sharing it here with everyone. And there is also the check for WRITE_CONTACTS
permission.
Here is the complete code for how to add phone number, email, website etc to an existing contact.
public static void addNumberToContact(Context context, Long contactRawId, String number) throws RemoteException, OperationApplicationException {
addInfoToAddressBookContact(
context,
contactRawId,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.TYPE_OTHER,
number
);
}
public static void addEmailToContact(Context context, Long contactRawId, String email) throws RemoteException, OperationApplicationException {
addInfoToAddressBookContact(
context,
contactRawId,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.TYPE,
ContactsContract.CommonDataKinds.Email.TYPE_OTHER,
email
);
}
public static void addURLToContact(Context context, Long contactRawId, String url) throws RemoteException, OperationApplicationException {
addInfoToAddressBookContact(
context,
contactRawId,
ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Website.URL,
ContactsContract.CommonDataKinds.Website.TYPE,
ContactsContract.CommonDataKinds.Website.TYPE_OTHER,
url
);
}
private static void addInfoToAddressBookContact(Context context, Long contactRawId, String mimeType, String whatToAdd, String typeKey, int type, String data) throws RemoteException, OperationApplicationException {
if(ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_DENIED) {
return;
}
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID, contactRawId)
.withValue(ContactsContract.Data.MIMETYPE, mimeType)
.withValue(whatToAdd, data)
.withValue(typeKey, type)
.build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}
I have similar problem. Spring 4 and Tomcat 8. I solve the problem with Spring configuration
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
<property name="initialSize" value="10" />
<property name="maxActive" value="25" />
<property name="maxIdle" value="20" />
<property name="minIdle" value="10" />
...
<property name="testOnBorrow" value="true" />
<property name="validationQuery" value="SELECT 1" />
</bean>
I have tested. It works well! This two line does everything in order to reconnect to database:
<property name="testOnBorrow" value="true" />
<property name="validationQuery" value="SELECT 1" />
One hint about the "background-size: cover" solution, you have to put it after "background" definition, otherwise it won't work, for example this won't work:
html, body {
height: 100%;
background-size: cover;
background:url("http://i.imgur.com/aZO5Kolb.jpg") no-repeat center center fixed;
}
To install 32-bit Java on Windows 7 (64-bit OS + Machine). You can do:
1) Download JDK: http://javadl.sun.com/webapps/download/AutoDL?BundleId=58124
2) Download JRE: http://www.java.com/en/download/installed.jsp?jre_version=1.6.0_22&vendor=Sun+Microsystems+Inc.&os=Linux&os_version=2.6.41.4-1.fc15.i686
3) System variable create: C:\program files (x86)\java\jre6\bin\
4) Anywhere you type java -version
it use 32-bit on (64-bit). I have to use this because lots of third party libraries do not work with 64-bit. Java wake up from the hell, give us peach :P. Go-language is killer.
I think you set the marquee width related to 5 images total width. It works fine
ex: <marquee style="width:700px"></marquee>
http://jsfiddle.net/jwB2Y/123/
The following CSS class force the label text to flow inline and get clipped if its length is more than max-length of the label.
.inline-label {
white-space: nowrap;
max-width: 150px;
overflow: hidden;
text-overflow: ellipsis;
float:left;
}
HTML:
<div>
<label for="id1" class="inline-label">This is the dummy text i want to display::</label>
<input type="text" id="id1"/>
</div>
This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570
I guess the counter-intuitive part of the question is: if this is correct C:
if (a == 1) {
int b = 10;
}
then why is this not also correct C?
if (a == 1)
int b = 10;
I mean, a one-line conditional if
statement should be fine either with or without braces, right?
The answer lies in the grammar of the if
statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10
line is a declaration, not a statement, and the grammar for the if
statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.
And just for the sake of answering the question completely -- this has nothing to do with scope. The b
variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror
anyways ;-)
(6.7) declaration: declaration-speci?ers init-declarator-listopt ; static_assert-declaration (6.7) init-declarator-list: init-declarator init-declarator-list , init-declarator (6.7) init-declarator: declarator declarator = initializer (6.8) statement: labeled-statement compound-statement expression-statement selection-statement iteration-statement jump-statement (6.8.2) compound-statement: { block-item-listopt } (6.8.4) selection-statement: if ( expression ) statement if ( expression ) statement else statement switch ( expression ) statement
Your first usage of Map
is inside a function in the combat
class. That happens before Map
is defined, hence the error.
A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map
is fully declared.
The solution is to follow the C++ pattern of the class declaration in a .h
file and the function bodies in a .cpp
. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.
I found one simple solution, just disable the Windows Indexing Services for the project folder and subfolders
I think you are looking for the Dictionary object, found in the Microsoft Scripting Runtime library. (Add a reference to your project from the Tools...References menu in the VBE.)
It pretty much works with any simple value that can fit in a variant (Keys can't be arrays, and trying to make them objects doesn't make much sense. See comment from @Nile below.):
Dim d As dictionary
Set d = New dictionary
d("x") = 42
d(42) = "forty-two"
d(CVErr(xlErrValue)) = "Excel #VALUE!"
Set d(101) = New Collection
You can also use the VBA Collection object if your needs are simpler and you just want string keys.
I don't know if either actually hashes on anything, so you might want to dig further if you need hashtable-like performance. (EDIT: Scripting.Dictionary does use a hash table internally.)
This never gonna work, you can't stringify your FormData object.
You should do this:
this.uploadFileToUrl = function(file, title, text, uploadUrl){
var fd = new FormData();
fd.append('title', title);
fd.append('text', text);
fd.append('file', file);
$http.post(uploadUrl, obj, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
blockUI.stop();
})
.error(function(error){
toaster.pop('error', 'Errore', error);
});
}
This should do it. You were missing a )
and you only need """
not 4 of them. Also you don't need a elif at the end.
ans=True
while ans:
print("""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Exit/Quit
""")
ans=raw_input("What would you like to do? ")
if ans=="1":
print("\nStudent Added")
elif ans=="2":
print("\n Student Deleted")
elif ans=="3":
print("\n Student Record Found")
elif ans=="4":
print("\n Goodbye")
ans = None
else:
print("\n Not Valid Choice Try again")
I would support the idea of creating a ftp group that will have the rights to upload. However, i don't think it is necessary to give 775 permission. 7 stands for read, write, execute. Normally you want to allow certain groups to read and write, but depending on the case, execute may not be necessary.
This code will print all the keys with maximum value
public class NewClass4 {
public static void main(String[] args)
{
HashMap<Integer,Integer>map=new HashMap<Integer, Integer>();
map.put(1, 50);
map.put(2, 60);
map.put(3, 30);
map.put(4, 60);
map.put(5, 60);
int maxValueInMap=(Collections.max(map.values())); // This will return max value in the Hashmap
for (Entry<Integer, Integer> entry : map.entrySet()) { // Itrate through hashmap
if (entry.getValue()==maxValueInMap) {
System.out.println(entry.getKey()); // Print the key with max value
}
}
}
}
SQL Server 2012 above, I prefer use format() function, more simplify.
SELECT format(date,'MM.yyyy') AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada
FROM [Order]
WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY format(date,'MM.yyyy')
I had the same problem because my "Dynamic Web Project" had no reference to the installed server i wanted to use and therefore had no reference to the Servlet API the server provides.
Following steps solved it without adding an extra Servlet-API to the Java Build Path (Eclipse version: Luna):
Edit: if there is no server listed you can create a new one on the Runtimes tab
I have the same warning (it's make my app cannot build). When I add C function
in Objective-C's .m file
, But forgot to declared it at .h
file.
If you use "firebase-functions" to host your sever-side-rendered application, you should be aware of this one:
error: Error: ENOENT: no such file or directory, open 'C:\Codes\url_shortener\functions\.env'
Means you have to store the .env file in the functions folder as well.
Found this one by:
console.log(require('dotenv').config())
You could use CSS to attain this. By specifying the list in the color and style of your choice, you can then also specify the text as a different color.
Follow the example at http://www.echoecho.com/csslists.htm.
This is the most popular (9500 stars) and light weight (20KB minify, 7.5KB minify+gzip) popup gallery I think: Magnific-Popup
With a Maven version of 3.5 or higher, you should be able to use a placeholder (e.g. ${revision}) in the parent section and inside the rest of the pom, you can use ${project.version}
.
Actually, you can also omit project properties outside of parent
which are the same, as they will be inherited. The result would look something like this:
<project>
<parent>
<artifactId>build.parent</artifactId>
<groupId>company</groupId>
<relativePath>../build.parent/pom.xml</relativePath>
<version>${revision}</version> <!-- use placeholder -->
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>artifact</artifactId>
<!-- no 'version', no 'groupId'; inherited from parent -->
<packaging>eclipse-plugin</packaging>
...
</project>
For more information, especially on how to resolve the placeholder during publishing, see Maven CI Friendly Versions | Multi Module Setup.
Padding and packing are just two aspects of the same thing:
In mystruct_A
, assuming a default alignment of 4, each member is aligned on a multiple of 4 bytes. Since the size of char
is 1, the padding for a
and c
is 4 - 1 = 3 bytes while no padding is required for int b
which is already 4 bytes. It works the same way for mystruct_B
.
In case you have a multi-module project :
let us say your module structure is
root-module
-> a-module
-> b-module
and the test(testToRun) you are looking to run is in b-module, with full path : com.xyz.b.module.TestClass.testToRun
As here you are interested to run the test in b-module, so you should see the tasks available for b-module.
./gradlew :b-module:tasks
The above command will list all tasks in b-module with description. And in ideal case, you will have a task named test to run the unit tests in that module.
./gradlew :b-module:test
Now, you have reached the point for running all the tests in b-module, finally you can pass a parameter to the above task to run tests which matches the certain path pattern
./gradlew :b-module:test --tests "com.xyz.b.module.TestClass.testToRun"
Now, instead of this if you run
./gradlew test --tests "com.xyz.b.module.TestClass.testToRun"
It will run the test task for both module a and b, which might result in failure as there is nothing matching the above pattern in a-module.
You can use 'skimage' library in Python
Example:
from skimage.io import imsave
imsave('Path_to_your_folder/File_name.jpg',your_array)
In Confluence 5.4.2 you can add surround your inline code with <code></code>
tags in the source editor thusly:
Confluence will show <code>this inline code</code> in a fixed font.
This can be useful where there are many fragments to modify since the double-brace feature only works when adding text interactively in the Confluence editor.
int random(int min, int max) //range : [min, max]
{
static bool first = true;
if (first)
{
srand( time(NULL) ); //seeding for the first time only!
first = false;
}
return min + rand() % (( max + 1 ) - min);
}
Try to place a
return 0;
on the end of your code or just erase the
void
from your main function I hope that I helped
You can find/debug XPath/CSS locators in the IE as well as in different browsers with the tool called SWD Page Recorder
The only restrictions/limitations:
IEDriverServer.exe
- should be downloaded separately and placed near SwdPageRecorder.exe
"Permission denied" prevents your script from being invoked at all. Thus, the only syntax that could be possibly pertinent is that of the first line (the "shebang"), which should look like #!/usr/bin/env bash
, or #!/bin/bash
, or similar depending on your target's filesystem layout.
Most likely the filesystem permissions not being set to allow execute. It's also possible that the shebang references something that isn't executable, but this is far less likely.
Mooted by the ease of repairing the prior issues.
The simple reading of
docker: Error response from daemon: oci runtime error: exec: "/usr/src/app/docker-entrypoint.sh": permission denied.
...is that the script isn't marked executable.
RUN ["chmod", "+x", "/usr/src/app/docker-entrypoint.sh"]
will address this within the container. Alternately, you can ensure that the local copy referenced by the Dockerfile is executable, and then use COPY
(which is explicitly documented to retain metadata).
Consider also using SETX
- it will set variable on user or machine (available for all users) level though the variable will be usable with the next opening of the cmd.exe ,so often it can be used together with SET
:
::setting variable for the current user
if not defined My_Var (
set "My_Var=My_Value"
setx My_Var My_Value
)
::setting machine defined variable
if not defined Global_Var (
set "Global_Var=Global_Value"
SetX Global_Var Global_Value /m
)
You can also edit directly the registry values:
User Variables: HKEY_CURRENT_USER\Environment
System Variables: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
Which will allow to avoid some restrictions of SET and SETX like the variables containing =
in their names.
from app import SQLAlchemyDB as db
Chance.query.filter(Chance.repo_id==repo_id,
Chance.status=="1",
db.func.date(Chance.apply_time)<=end,
db.func.date(Chance.apply_time)>=start).count()
it is equal to:
select
count(id)
from
Chance
where
repo_id=:repo_id
and status='1'
and date(apple_time) <= end
and date(apple_time) >= start
wish can help you.
You can also use functions with $filter('filter')
:
var foo = $filter('filter')($scope.results.subjects, function (item) {
return item.grade !== 'A';
});
In CakePHP 1.3, use 'default'=>value
to select the default value in a select input:
$this->Form->input('Leaf.id', array('type'=>'select', 'label'=>'Leaf', 'options'=>$leafs, 'default'=>'3'));
mvn install
will put your packaged maven project into the local repository, for local application using your project as a dependency.mvn release
will basically put your current code in a tag on your SCM, change your version in your projects.mvn deploy
will put your packaged maven project into a remote repository for sharing with other developers.Resources :
The process of creating executables for many platforms can be a little tedious, so I suggest to use a script:
#!/usr/bin/env bash
package=$1
if [[ -z "$package" ]]; then
echo "usage: $0 <package-name>"
exit 1
fi
package_name=$package
#the full list of the platforms: https://golang.org/doc/install/source#environment
platforms=(
"darwin/386"
"dragonfly/amd64"
"freebsd/386"
"freebsd/amd64"
"freebsd/arm"
"linux/386"
"linux/amd64"
"linux/arm"
"linux/arm64"
"netbsd/386"
"netbsd/amd64"
"netbsd/arm"
"openbsd/386"
"openbsd/amd64"
"openbsd/arm"
"plan9/386"
"plan9/amd64"
"solaris/amd64"
"windows/amd64"
"windows/386" )
for platform in "${platforms[@]}"
do
platform_split=(${platform//\// })
GOOS=${platform_split[0]}
GOARCH=${platform_split[1]}
output_name=$package_name'-'$GOOS'-'$GOARCH
if [ $GOOS = "windows" ]; then
output_name+='.exe'
fi
env GOOS=$GOOS GOARCH=$GOARCH go build -o $output_name $package
if [ $? -ne 0 ]; then
echo 'An error has occurred! Aborting the script execution...'
exit 1
fi
done
I checked this script on OSX only
A dangling pointer points to memory that has already been freed. The storage is no longer allocated. Trying to access it might cause a Segmentation fault.
Common way to end up with a dangling pointer:
char *func()
{
char str[10];
strcpy(str, "Hello!");
return str;
}
//returned pointer points to str which has gone out of scope.
You are returning an address which was a local variable, which would have gone out of scope by the time control was returned to the calling function. (Undefined behaviour)
Another common dangling pointer example is an access of a memory location via pointer, after free has been explicitly called on that memory.
int *c = malloc(sizeof(int));
free(c);
*c = 3; //writing to freed location!
A memory leak is memory which hasn't been freed, there is no way to access (or free it) now, as there are no ways to get to it anymore. (E.g. a pointer which was the only reference to a memory location dynamically allocated (and not freed) which points somewhere else now.)
void func(){
char *ch = malloc(10);
}
//ch not valid outside, no way to access malloc-ed memory
Char-ptr ch is a local variable that goes out of scope at the end of the function, leaking the dynamically allocated 10 bytes.
Since there are many different kinds of casting each with different semantics, static_cast<> allows you to say "I'm doing a legal conversion from one type to another" like from int to double. A plain C-style cast can mean a lot of things. Are you up/down casting? Are you reinterpreting a pointer?
No code change required:
While you are in debug mode within the catch {...}
block open up the "QuickWatch" window (Ctrl+Alt+Q) and paste in there:
((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors
or:
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
If you are not in a try/catch or don't have access to the exception object.
This will allow you to drill down into the ValidationErrors
tree. It's the easiest way I've found to get instant insight into these errors.
It's db1.dbo.TempTable and db2.dbo.TempTable
The four-part naming scheme goes:
ServerName.DatabaseName.Schema.Object
<input type="text" name="whatever" id="funkystyling" />
Here's the CSS for the image on the left:
#funkystyling {
background: white url(/path/to/icon.png) left no-repeat;
padding-left: 17px;
}
And here's the CSS for the image on the right:
#funkystyling {
background: white url(/path/to/icon.png) right no-repeat;
padding-right: 17px;
}
If you're up for it, use the DateTime class
Delete node folder completely from program file folder. Uninstall node.js and then reinstall it. change Path of environment variable PATH. delete .npmrc file from C:\users\yourusername
The main difference between logging in with a postgres user or any other user created by us, is that when using the postgres user it is NOT necessary to specify the host with -h and instead for another user if.
$ psql -U postgres
# CREATE ROLE usertest LOGIN PASSWORD 'pwtest';
# CREATE DATABASE dbtest WITH OWNER = usertest;
# SHOW port;
# \q
$ psql -h localhost -d dbtest -U usertest -p 5432
GL
In eclipse I included a compressed jar file i.e. zip file. Eclipse allowed me to add this zip file as an external jar but when I tried to access the classes in the jar they weren't showing up.
After a lot of trial and error I found that using a zip format doesn't work. When I added a jar file then it worked for me.
from datetime import datetime
start_date = datetime.strptime('8/18/2008', "%m/%d/%Y")
end_date = datetime.strptime('9/26/2008', "%m/%d/%Y")
print abs((end_date-start_date).days)
This worked for me:
<video src="file.mp4" controls style="max-width:100%; height:auto"></video>
Simply do this:
<object data="resume.pdf" type="application/pdf" width="100%" height="800px">
<p>It appears you don't have a PDF plugin for this browser.
No biggie... you can <a href="resume.pdf">click here to
download the PDF file.</a></p>
</object>
Both algorithms (AES and twofish) are considered very secure. This has been widely covered in other answers.
However, since AES is much widely used now in 2016, it has been specifically hardware-accelerated in several platforms such as ARM and x86. While not significantly faster than twofish before hardware acceleration, AES is now much faster thanks to the dedicated CPU instructions.
There is a built-in library called pickle
. Using pickle
you can dump objects to a file and load them later.
import pickle
f = open('store.pckl', 'wb')
pickle.dump(obj, f)
f.close()
f = open('store.pckl', 'rb')
obj = pickle.load(f)
f.close()
1) Check the CodeFile property in <%@Page CodeFile="filename.aspx.cs" %> in "filename.aspx" page , your Code behind file name and this Property name should be same.
2)you may miss runat="server" in code
In the case of delegated event handlers, where you might have something like this:
<ul>
<li data-id="1">
<span>Item 1</span>
</li>
<li data-id="2">
<span>Item 2</span>
</li>
<li data-id="3">
<span>Item 3</span>
</li>
<li data-id="4">
<span>Item 4</span>
</li>
<li data-id="5">
<span>Item 5</span>
</li>
</ul>
and your JS code like so:
$(document).ready(function() {
$('ul').on('click li', function(event) {
var $target = $(event.target),
itemId = $target.data('id');
//do something with itemId
});
});
You'll more than likely find that itemId is undefined
, as the content of the LI is wrapped in a <span>
, which means the <span>
will probably be the event target. You can get around this with a small check, like so:
$(document).ready(function() {
$('ul').on('click li', function(event) {
var $target = $(event.target).is('li') ? $(event.target) : $(event.target).closest('li'),
itemId = $target.data('id');
//do something with itemId
});
});
Or, if you prefer to maximize readability (and also avoid unnecessary repetition of jQuery wrapping calls):
$(document).ready(function() {
$('ul').on('click li', function(event) {
var $target = $(event.target),
itemId;
$target = $target.is('li') ? $target : $target.closest('li');
itemId = $target.data('id');
//do something with itemId
});
});
When using event delegation, the .is()
method is invaluable for verifying that your event target (among other things) is actually what you need it to be. Use .closest(selector)
to search up the DOM tree, and use .find(selector)
(generally coupled with .first()
, as in .find(selector).first()
) to search down it. You don't need to use .first()
when using .closest()
, as it only returns the first matching ancestor element, while .find()
returns all matching descendants.
I've used this with Jackson 2.x and Spring 3.1.2+
servlet-context.xml:
Note that the root element is <beans:beans>
, so you may need to remove beans
and add mvc
to some of these elements depending on your setup.
<annotation-driven>
<message-converters>
<beans:bean
class="org.springframework.http.converter.StringHttpMessageConverter" />
<beans:bean
class="org.springframework.http.converter.ResourceHttpMessageConverter" />
<beans:bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<beans:property name="objectMapper" ref="jacksonObjectMapper" />
</beans:bean>
</message-converters>
</annotation-driven>
<beans:bean id="jacksonObjectMapper"
class="au.edu.unimelb.atcom.transfer.json.mappers.JSONMapper" />
au.edu.unimelb.atcom.transfer.json.mappers.JSONMapper.java:
public class JSONMapper extends ObjectMapper {
public JSONMapper() {
SimpleModule module = new SimpleModule("JSONModule", new Version(2, 0, 0, null, null, null));
module.addSerializer(Date.class, new DateSerializer());
module.addDeserializer(Date.class, new DateDeserializer());
// Add more here ...
registerModule(module);
}
}
DateSerializer.java:
public class DateSerializer extends StdSerializer<Date> {
public DateSerializer() {
super(Date.class);
}
@Override
public void serialize(Date date, JsonGenerator json,
SerializerProvider provider) throws IOException,
JsonGenerationException {
// The client side will handle presentation, we just want it accurate
DateFormat df = StdDateFormat.getBlueprintISO8601Format();
String out = df.format(date);
json.writeString(out);
}
}
DateDeserializer.java:
public class DateDeserializer extends StdDeserializer<Date> {
public DateDeserializer() {
super(Date.class);
}
@Override
public Date deserialize(JsonParser json, DeserializationContext context)
throws IOException, JsonProcessingException {
try {
DateFormat df = StdDateFormat.getBlueprintISO8601Format();
return df.parse(json.getText());
} catch (ParseException e) {
return null;
}
}
}
push()
is for arrays, not objects, so use the right data structure.
var data = [];
// ...
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };
// ...
var tempData = [];
for ( var index=0; index<data.length; index++ ) {
if ( data[index].Status == "Valid" ) {
tempData.push( data );
}
}
data = tempData;
I have encountered this error and it is caused by wrong "owner/group" of the file/folder. You must seek assistance to your server admin to change the "owner/group" of this file/folder and retry using "git pull" again. Or if you are a sudoer, just sudo chown "your owner name / your group name" and try again pulling your repository. Try it, it works 100% to me!
Based on this answer
<input type="text" id="sno" placeholder="Only float with dot !"
onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||
event.charCode == 46 || event.charCode == 0 ">
Meaning :
Char code :
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Backspace
(otherwise need refresh page on Firefox)dot
&&
is AND
, ||
is OR
operator.
if you try float with comma :
<input type="text" id="sno" placeholder="Only float with comma !"
onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||
event.charCode == 44 || event.charCode == 0 ">
Supported Chromium and Firefox (Linux X64)(other browsers I does not exist.)
%20
is the space between AmberCRO SOP.
Try -
href="http://file:///K:/AmberCRO SOP/2011-07-05/SOP-SOP-3.0.pdf"
Or rename the folder as AmberCRO-SOP and write it as -
href="http://file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf"
Replace your domain with domainname.com
, it's working with me .
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domainname\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domainname.com/$1 [R,L]
I was getting this error : javax.faces.application.ViewExpiredException.When I using different requests, I found those having same JsessionId, even after restarting the server. So this is due to the browser cache. Just close the browser and try, it will work.
Simple Way to add JTextArea in JScrollBar with JScrollPan
import javax.swing.*;
public class ScrollingTextArea
{
JFrame f;
JTextArea ta;
JScrollPane scrolltxt;
public ScrollingTextArea()
{
// TODO Auto-generated constructor stub
f=new JFrame();
f.setLayout(null);
f.setVisible(true);
f.setSize(500,500);
ta=new JTextArea();
ta.setBounds(5,5,100,200);
scrolltxt=new JScrollPane(ta);
scrolltxt.setBounds(3,3,400,400);
f.add(scrolltxt);
}
public static void main(String[] args)
{
new ScrollingTextArea();
}
}
if you use this way :
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
fmt.Println(dir)
you will get the /tmp path when you are running program using some IDE like GoLang because the executable will save and run from /tmp
i think the best way for getting the currentWorking Directory or '.' is :
import(
"os"
"fmt"
"log"
)
func main() {
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
fmt.Println(dir)
}
the os.Getwd() function will return the current working directory. and its all without using of any external library :D
You are not forced to put it all on one line:-
x = y==1 ?
2
:// else
3;
It is much clearer than if/else because you can see immediately that both branches lead to x being assigned to.
Date.js is a handy library for manipulating and formatting dates. It can help in this situation.
Here's another:
data[data$Code == "A" | data$Code == "B", ]
It's also worth mentioning that the subsetting factor doesn't have to be part of the data frame if it matches the data frame rows in length and order. In this case we made our data frame from this factor anyway. So,
data[Code == "A" | Code == "B", ]
also works, which is one of the really useful things about R.
There is a statistics library if you are using python >= 3.4
https://docs.python.org/3/library/statistics.html
You may use it's mean method like this. Let's say you have a list of numbers of which you want to find mean:-
list = [11, 13, 12, 15, 17]
import statistics as s
s.mean(list)
It has other methods too like stdev, variance, mode, harmonic mean, median etc which are too useful.
I make it simple, if the layout is same i just put the intent it.
My code like this:
public class RegistrationMenuActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnCertificate, btnSeminarKit;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration_menu);
initClick();
}
private void initClick() {
btnCertificate = (Button) findViewById(R.id.btn_Certificate);
btnCertificate.setOnClickListener(this);
btnSeminarKit = (Button) findViewById(R.id.btn_SeminarKit);
btnSeminarKit.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_Certificate:
break;
case R.id.btn_SeminarKit:
break;
}
Intent intent = new Intent(RegistrationMenuActivity.this, ScanQRCodeActivity.class);
startActivity(intent);
}
}
You have to reconfigure the FlutterSDK path in Android Studio: Go to Setting -> Language & Frameworks -> Flutter and set the path to Flutter SDK
Entity Framework does not support collections of primitive types. You can either create an entity (which will be saved to a different table) or do some string processing to save your list as a string and populate the list after the entity is materialized.
Could it be a problem with past preview versions of Android Studio ? nowadays "beta" has replaced the "preview". I try it out step by step debugging while using Memory Monitor at same time by Android Studio (Beta) 0.8.11 on OSX 10.9.5 without any problems.
The tutorial Debugging with Android Studio also helps, specially this paragraph :
Here a couple of screenshot while debugging step by step on a breakpoint a monitoring the memory on the emulator:
You don't need the jsp:useBean
to set the model if you already have a controller which prepared the model.
Just access it plain by EL:
<p>${Questions.questionPaperID}</p>
<p>${Questions.question}</p>
or by JSTL <c:out>
tag if you'd like to HTML-escape the values or when you're still working on legacy Servlet 2.3 containers or older when EL wasn't supported in template text yet:
<p><c:out value="${Questions.questionPaperID}" /></p>
<p><c:out value="${Questions.question}" /></p>
Unrelated to the problem, the normal practice is by the way to start attribute name with a lowercase, like you do with normal variable names.
session.setAttribute("questions", questions);
and alter EL accordingly to use ${questions}
.
Also note that you don't have any JSTL tag in your code. It's all plain JSP.
Just to add to Daniel's answer (which is great! and absolutely right!), version without JQuery:
function objOff(obj)
{
var currleft = currtop = 0;
if( obj.offsetParent )
{ do { currleft += obj.offsetLeft; currtop += obj.offsetTop; }
while( obj = obj.offsetParent ); }
else { currleft += obj.offsetLeft; currtop += obj.offsetTop; }
return [currleft,currtop];
}
function FontMetric(fontName,fontSize)
{
var text = document.createElement("span");
text.style.fontFamily = fontName;
text.style.fontSize = fontSize + "px";
text.innerHTML = "ABCjgq|";
// if you will use some weird fonts, like handwriting or symbols, then you need to edit this test string for chars that will have most extreme accend/descend values
var block = document.createElement("div");
block.style.display = "inline-block";
block.style.width = "1px";
block.style.height = "0px";
var div = document.createElement("div");
div.appendChild(text);
div.appendChild(block);
// this test div must be visible otherwise offsetLeft/offsetTop will return 0
// but still let's try to avoid any potential glitches in various browsers
// by making it's height 0px, and overflow hidden
div.style.height = "0px";
div.style.overflow = "hidden";
// I tried without adding it to body - won't work. So we gotta do this one.
document.body.appendChild(div);
block.style.verticalAlign = "baseline";
var bp = objOff(block);
var tp = objOff(text);
var taccent = bp[1] - tp[1];
block.style.verticalAlign = "bottom";
bp = objOff(block);
tp = objOff(text);
var theight = bp[1] - tp[1];
var tdescent = theight - taccent;
// now take it off :-)
document.body.removeChild(div);
// return text accent, descent and total height
return [taccent,theight,tdescent];
}
I've just tested the code above and works great on latest Chrome, FF and Safari on Mac.
EDIT: I have added font size as well and tested with webfont instead of system font - works awesome.
If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.
For some cases UIWebView is a good solution. Because:
Using NSAttributedString can lead to crashes, if html is complex or contains tables (so example)
For loading text to web view you can use the following snippet (just example):
func loadHTMLText(_ text: String?, font: UIFont) {
let fontSize = font.pointSize * UIScreen.screens[0].scale
let html = """
<html><body><span style=\"font-family: \(font.fontName); font-size: \(fontSize)\; color: #112233">\(text ?? "")</span></body></html>
"""
self.loadHTMLString(html, baseURL: nil)
}
Using this:
<input type="file" accept="image/*">
works in both FF and Chrome.
I use GUIDs as random keys for database type operations.
The hexadecimal form, with the dashes and extra characters seem unnecessarily long to me. But I also like that strings representing hexadecimal numbers are very safe in that they do not contain characters that can cause problems in some situations such as '+','=', etc..
Instead of hexadecimal, I use a url-safe base64 string. The following does not conform to any UUID/GUID spec though (other than having the required amount of randomness).
import base64
import uuid
# get a UUID - URL safe, Base64
def get_a_uuid():
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return r_uuid.replace('=', '')
Cleanest way I have come across is inspired by the sql style guide.
sql = """
SELECT field1, field2, field3, field4
FROM table
WHERE condition1 = 1
AND condition2 = 2;
"""
Essentially, the keywords that begin a clause should be right-aligned and the field names etc, should be left aligned. This looks very neat and is easier to debug as well.
Open app page on Google Play:
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + context.getPackageName()));
startActivity(intent);
I took couple of ideas from your answers and I don't know how to make it shorter :)
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris['feature_names'])
df['target'] = iris['target']
This gives a Pandas DataFrame with feature_names plus target as columns and RangeIndex(start=0, stop=len(df), step=1). I would like to have a shorter code where I can have 'target' added directly.
// The integer I want to convert
int myInt = 100;
// Casting of integer to float
float newFloat = (float) myInt
In my use case, I wanted to asynchronously retrieve a url, and then follow that url to an external resource in a new window. A directive seemed overkill because I don't need reusability, so I simply did:
<button (click)="navigateToResource()">Navigate</button>
And in my component.ts
navigateToResource(): void {
this.service.getUrl((result: any) => window.open(result.url));
}
Routing to a link indirectly like this will likely trigger the browser's popup blocker.
A word of caution:
In my experience, omitting the href
attribute causes problems for accessibility as the keyboard navigation will ignore it and never give it focus like it will when href is present. Manually including your element in the tabindex is a way around that.
For your stated desire to "check if a property exists" you can directly use Lo-Dash's has
.
var exists = _.has(myObject, propertyNameToCheck);
I believe if you used the double
data type, the re-calculation in Excel would work just fine.
I wonder why nobody proposed the possibly simplest solution:
don't use a
<form>
A <whatever ng-form>
does IMHO a better job and without an HTML form, there's nothing to be submitted by the browser itself. Which is exactly the right behavior when using angular.
Here is the alternative solution to check whether a particular string contains some predefined string. It uses IndexOf
Function:
'this is your string
Dim strMyString As String = "aaSomethingbb"
'if your string contains these strings
Dim TargetString1 As String = "Something"
Dim TargetString2 As String = "Something2"
If strMyString.IndexOf(TargetString1) <> -1 Or strMyString.IndexOf(TargetString2) <> -1 Then
End If
NOTE: This solution has been tested with Visual Studio 2010.
There are already great methods already mentioned on this page, however it does seem a little obscure as to which to use. So I have added some mesurements so you can more easily decide for yourself:
A large number has been used (for overhead) 1111111111111122222222222222222333333333333333333333
map(int, str(num))
:import timeit
def method():
num = 1111111111111122222222222222222333333333333333333333
return map(int, str(num))
print(timeit.timeit("method()", setup="from __main__ import method", number=10000)
Output: 0.018631496999999997
import timeit
def method():
num = 1111111111111122222222222222222333333333333333333333
return [int(x) for x in str(num)]
print(timeit.timeit("method()", setup="from __main__ import method", number=10000))
Output: 0.28403817900000006
Code taken from this answer
The results show that the first method involving inbuilt methods is much faster than list comprehension.
import timeit
def method():
q = 1111111111111122222222222222222333333333333333333333
ret = []
while q != 0:
q, r = divmod(q, 10) # Divide by 10, see the remainder
ret.insert(0, r) # The remainder is the first to the right digit
return ret
print(timeit.timeit("method()", setup="from __main__ import method", number=10000))
Output: 0.38133582499999996
Code taken from this answer
list(str(123))
method (does not provide the right output):import timeit
def method():
return list(str(1111111111111122222222222222222333333333333333333333))
print(timeit.timeit("method()", setup="from __main__ import method", number=10000))
Output: 0.028560138000000013
Code taken from this answer
import timeit
def method():
n = 1111111111111122222222222222222333333333333333333333
l = []
while n != 0:
l = [n % 10] + l
n = n // 10
return l
print(timeit.timeit("method()", setup="from __main__ import method", number=10000))
Output: 0.37039988200000007
Code taken from this answer
In all cases the map(int, str(num))
is the fastest method (and is therefore probably the best method to use). List comprehension is the second fastest (but the method using map(int, str(num))
is probably the most desirable of the two.
Those that reinvent the wheel are interesting but are probably not so desirable in real use.
for /f "tokens=* delims= " %%f in (myfile) do
This reads a file line-by-line, removing leading spaces (thanks, jeb).
set line=%%f
sets then the line
variable to the line just read and
call :procesToken
calls a subroutine that does something with the line
:processToken
is the start of the subroutine mentioned above.
for /f "tokens=1* delims=/" %%a in ("%line%") do
will then split the line at /
, but stopping tokenization after the first token.
echo Got one token: %%a
will output that first token and
set line=%%b
will set the line
variable to the rest of the line.
if not "%line%" == "" goto :processToken
And if line
isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.
You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.
Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.
You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.
The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.
You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.
Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.
But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).
You should provide @2x images for the Retina Macbook Pro and future Retina Macs.
If it is something to do with the data in your database, why not utilize database isolation locking to achieve?
I'm facing same problem and so far I found:
new Uri(Request.Url,Request.ApplicationPath)
or
Request.Url.GetLeftPart(UriPartial.Authority)+Request.ApplicationPath
How about check and then set dict element without processing all indexes twice?
Solution:
def nested_yield(nested, keys_list):
"""
Get current nested data by send(None) method. Allows change it to Value by calling send(Value) next time
:param nested: list or dict of lists or dicts
:param keys_list: list of indexes/keys
"""
if not len(keys_list): # assign to 1st level list
if isinstance(nested, list):
while True:
nested[:] = yield nested
else:
raise IndexError('Only lists can take element without key')
last_key = keys_list.pop()
for key in keys_list:
nested = nested[key]
while True:
try:
nested[last_key] = yield nested[last_key]
except IndexError as e:
print('no index {} in {}'.format(last_key, nested))
yield None
Example workflow:
ny = nested_yield(nested_dict, nested_address)
data_element = ny.send(None)
if data_element:
# process element
...
else:
# extend/update nested data
ny.send(new_data_element)
...
ny.close()
Test
>>> cfg= {'Options': [[1,[0]],[2,[4,[8,16]]],[3,[9]]]}
ny = nested_yield(cfg, ['Options',1,1,1])
ny.send(None)
[8, 16]
>>> ny.send('Hello!')
'Hello!'
>>> cfg
{'Options': [[1, [0]], [2, [4, 'Hello!']], [3, [9]]]}
>>> ny.close()
The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.
If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.
(SELECT CASE WHEN (SELECT Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 )=0 THEN 'Pending'
WHEN (SELECT Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 AND )<>0 THEN (SELECT CASE WHEN ISNULL(ChequeNo,0) IS NOT NULL THEN 'Deposit' ELSE 'Pending' END AS Deposite FROM tbl_EEsi WHERE AND (Month= 1) AND (Year = 2020) AND )END AS Stat)
You can create a unique index that accept multiple NULLs with a WHERE
clause. See the answer below.
You cannot create a UNIQUE constraint and allow NULLs. You need set a default value of NEWID().
Update the existing values to NEWID() where NULL before creating the UNIQUE constraint.
<iframe src="http://docs.google.com/gview?url=http://domain.com/pdf.pdf&embedded=true"
style="width:600px; height:500px;" frameborder="0"></iframe>
Google docs allows you to embed PDFs, Microsoft Office Docs, and other applications by just linking to their services with an iframe. Its user-friendly, versatile, and attractive.
It is already said in other answers . I did it like placing Spinner inside a CardView and changed the cardBackgroundColor . You could use some other views also and set its background either drawable or color . Thus it doesn't affect Spinner drop down arrow. As the spinner dropdown arrow disappears if we set background to Spinner.
<androidx.cardview.widget.CardView
android:id="@+id/cardView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardCornerRadius="6dp"
app:cardBackgroundColor="@color/white">
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"/>
</androidx.cardview.widget.CardView>
I organize packages by feature, not by patterns or implementation roles. I think packages like:
beans
factories
collections
are wrong.
I prefer, for example:
orders
store
reports
so I can hide implementation details through package visibility. Factory of orders should be in the orders
package so details about how to create an order are hidden.
By default , maven looks at these folders for java and test classes respectively - src/main/java and src/test/java
When the src is specified with the test classes under source and the scope for junit dependency in pom.xml is mentioned as test - org.unit will not be found by maven.
The only way I know to deal with this is to create a new workspace, import projects from the polluted workspace, reconstructing all my settings (a major pain) and then delete the old workspace. Is there an easier way to deal with this?
For synchronizing or restoring all our settings we use Workspace Mechanic. Once all the settings are recorded its one click and all settings are restored... You can also setup a server which provides those settings for all users.
In General:
An example of an easy way to post XML data and get the response (as a string) would be the following function:
public string postXMLData(string destinationUrl, string requestXml)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
return null;
}
In your specific situation:
Instead of:
request.ContentType = "application/x-www-form-urlencoded";
use:
request.ContentType = "text/xml; encoding='utf-8'";
Also, remove:
string postData = "XMLData=" + Sendingxml;
And replace:
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
with:
byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());
Two options save vijay.sql
declare
begin
execute immediate
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||to_char(sysdate,'YYYYMMDD')||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
sel.tactical_select_executive_flag,
sel.agent_name,
res.DMS_RESIGN_CAMPAIGN_CODE,
pclub.tactical_select_flag
FROM spineowner.pop_wkly_refresh_20100201 wk,
dms_bb_coverage_102009 bbc,
dms_select_executive_group sel,
DMS_RESIGN_CAMPAIGN_26052009 res,
DMS_PRIORITY_CLUB pclub
WHERE wk.mpn = bbc.mpn(+)
AND wk.mpn = sel.mpn (+)
AND wk.mpn = res.mpn (+)
AND wk.mpn = pclub.mpn (+)'
end;
/
The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as
declare
begin
execute immediate
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||&1||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
sel.tactical_select_executive_flag,
sel.agent_name,
res.DMS_RESIGN_CAMPAIGN_CODE,
pclub.tactical_select_flag
FROM spineowner.pop_wkly_refresh_20100201 wk,
dms_bb_coverage_102009 bbc,
dms_select_executive_group sel,
DMS_RESIGN_CAMPAIGN_26052009 res,
DMS_PRIORITY_CLUB pclub
WHERE wk.mpn = bbc.mpn(+)
AND wk.mpn = sel.mpn (+)
AND wk.mpn = res.mpn (+)
AND wk.mpn = pclub.mpn (+)'
end;
/
and then run as sqlplus -s username/password @vijay.sql '20100101'
Find can be used to print out the file-size in bytes with %s as a printf. %h/%f prints the directory prefix and filename respectively. \n forces a newline.
Example
find . -size +10000k -printf "%h/%f,%s\n"
Output
./DOTT/extract/DOTT/TENTACLE.001,11358470
./DOTT/Day Of The Tentacle.nrg,297308316
./DOTT/foo.iso,297001116
hai the most easiest way is this:
add this code to mainactivity.java
public void start(View view) {
stop.setBackgroundResource(R.color.red);
start.setBackgroundResource(R.color.yellow);
}
public void stop(View view) {
stop.setBackgroundResource(R.color.yellow);
start.setBackgroundResource(R.color.red);
}
and then in your activity main
<button android:id="@+id/start" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="start" android:text="Click">
</button><button android:id="@+id/stop" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="stop" android:text="Click">
or follow along this tutorial
For identifying NaN
values use boolean indexing
:
print(df[df['x'].isnull()])
Then for removing all non-numeric values use to_numeric
with parameter errors='coerce'
- to replace non-numeric values to NaN
s:
df['x'] = pd.to_numeric(df['x'], errors='coerce')
And for remove all rows with NaN
s in column x
use dropna
:
df = df.dropna(subset=['x'])
Last convert values to int
s:
df['x'] = df['x'].astype(int)
Because the compiled JavaScript has all the type information erased, you can't use T
to new up an object.
You can do this in a non-generic way by passing the type into the constructor.
class TestOne {
hi() {
alert('Hi');
}
}
class TestTwo {
constructor(private testType) {
}
getNew() {
return new this.testType();
}
}
var test = new TestTwo(TestOne);
var example = test.getNew();
example.hi();
You could extend this example using generics to tighten up the types:
class TestBase {
hi() {
alert('Hi from base');
}
}
class TestSub extends TestBase {
hi() {
alert('Hi from sub');
}
}
class TestTwo<T extends TestBase> {
constructor(private testType: new () => T) {
}
getNew() : T {
return new this.testType();
}
}
//var test = new TestTwo<TestBase>(TestBase);
var test = new TestTwo<TestSub>(TestSub);
var example = test.getNew();
example.hi();
Use COPY command like this:
COPY foo.txt /data/foo.txt
# where foo.txt is the relative path on host
# and /data/foo.txt is the absolute path in the image
read more details for COPY in the official documentation
An alternative would be to use ADD but this is not the best practise if you dont want to use some advanced features of ADD like decompression of tar.gz files.If you still want to use ADD command, do it like this:
ADD abc.txt /data/abc.txt
# where abc.txt is the relative path on host
# and /data/abc.txt is the absolute path in the image
read more details for ADD in the official documentation
This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub.
You may want to add logic to sort your monthly data after it's all been copied
Public Sub MoveData(MonthNumber As Integer, SheetName As String)
Dim sharePoint As Worksheet
Dim Month As Worksheet
Dim spRange As Range
Dim cell As Range
Set sharePoint = Sheets("Sharepoint")
Set Month = Sheets(SheetName)
Set spRange = sharePoint.Range("A2")
Set spRange = sharePoint.Range("A2:" & spRange.End(xlDown).Address)
For Each cell In spRange
If Format(cell.Value, "MM") = MonthNumber Then
copyRowTo sharePoint.Range(cell.Row & ":" & cell.Row), Month
End If
Next cell
End Sub
Sub copyRowTo(rng As Range, ws As Worksheet)
Dim newRange As Range
Set newRange = ws.Range("A1")
If newRange.Offset(1).Value <> "" Then
Set newRange = newRange.End(xlDown).Offset(1)
Else
Set newRange = newRange.Offset(1)
End If
rng.Copy
newRange.PasteSpecial (xlPasteAll)
End Sub
You can use AJAX for that. Whenever you scan a barcode, your scanner will act as if it is a keyboard typing into your input type="text"
components. With JavaScript, capture the corresponding event, and send HTTP REQUEST and process responses accordingly.
You can try also with userInput.bat which uses the html input element.
This will assign the input to the value jstackId:
call userInput.bat jstackId
echo %jstackId%
This will just print the input value which eventually you can capture with FOR /F
:
call userInput.bat
git lfs migrate import --include="fpss.tar.gz"
this should re-write your local commits with the new lfs refs
The first button is always the default; it can't be changed. Whilst you can try to fix it up with JavaScript, the form will behave unexpectedly in a browser without scripting, and there are some usability/accessibility corner cases to think about. For example, the code linked to by Zoran will accidentally submit the form on Enter press in a <input type="button">
, which wouldn't normally happen, and won't catch IE's behaviour of submitting the form for Enter press on other non-field content in the form. So if you click on some text in a <p>
in the form with that script and press Enter, the wrong button will be submitted... especially dangerous if, as given in that example, the real default button is ‘Delete’!
My advice would be to forget about using scripting hacks to reassign defaultness. Go with the flow of the browser and just put the default button first. If you can't hack the layout to give you the on-screen order you want, then you can do it by having a dummy invisible button first in the source, with the same name/value as the button you want to be default:
<input type="submit" class="defaultsink" name="COMMAND" value="Save" />
.defaultsink {
position: absolute; left: -100%;
}
(note: positioning is used to push the button off-screen because display: none
and visibility: hidden
have browser-variable side-effects on whether the button is taken as default and whether it's submitted.)
Below is a fully functional example of what I believe you're trying to do (with a functional snippet).
Based on your question, you seem to be modifying 1 property in state
for all of your elements. That's why when you click on one, all of them are being changed.
In particular, notice that the state tracks an index of which element is active. When MyClickable
is clicked, it tells the Container
its index, Container
updates the state
, and subsequently the isActive
property of the appropriate MyClickable
s.
class Container extends React.Component {_x000D_
state = {_x000D_
activeIndex: null_x000D_
}_x000D_
_x000D_
handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
render() {_x000D_
return <div>_x000D_
<MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
<MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
<MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
</div>_x000D_
}_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
handleClick = () => this.props.onClick(this.props.index)_x000D_
_x000D_
render() {_x000D_
return <button_x000D_
type='button'_x000D_
className={_x000D_
this.props.isActive ? 'active' : 'album'_x000D_
}_x000D_
onClick={ this.handleClick }_x000D_
>_x000D_
<span>{ this.props.name }</span>_x000D_
</button>_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
display: block;_x000D_
margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable
elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.
// New render method for `Container`
render() {
const clickables = [
{ name: "a" },
{ name: "b" },
{ name: "c" },
]
return <div>
{ clickables.map(function(clickable, i) {
return <MyClickable key={ clickable.name }
name={ clickable.name }
index={ i }
isActive={ this.state.activeIndex === i }
onClick={ this.handleClick }
/>
} )
}
</div>
}
SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')
Use console.log(JSON.stringify(result))
to get the JSON in a string format.
EDIT: If your intention is to get the id and other properties from the result object and you want to see it console to know if its there then you can check with hasOwnProperty
and access the property if it does exist:
var obj = {id : "007", name : "James Bond"};
console.log(obj); // Object { id: "007", name: "James Bond" }
console.log(JSON.stringify(obj)); //{"id":"007","name":"James Bond"}
if (obj.hasOwnProperty("id")){
console.log(obj.id); //007
}
Heh tried all these answers and none of them worked. I think a common cause of this issue is something a lot simpler.
I advise all who get this problem to look at their launch configuration:
Look! The launch configuration contains options for which APK to deploy. If you choose default, Android Studio will be dumb to any product flavors, build types etc. you have in your gradle file. In my case, I have multiple build types and product flavors, and received "no local path" when trying to launch a non-default product flavor.
Android Studio was not wrong! It couldn't find the default APK, because I was not building for it. I solve my issue by instead choosing "Do not deploy anything" and then executing the gradle install task I needed for my specific combination of product flavor / build type.
Yes you right and I just want to make it understandable for complete beginners.
<link rel="shortcut icon" href="images/favicon.ico" />
and past it without any changes in between <head>
opening and </head>
closing tag.Below is the code for pass unique notification id:
//"CommonUtilities.getValudeFromOreference" is the method created by me to get value from savedPreferences.
String notificationId = CommonUtilities.getValueFromPreference(context, Global.NOTIFICATION_ID, "0");
int notificationIdinInt = Integer.parseInt(notificationId);
notificationManager.notify(notificationIdinInt, notification);
// will increment notification id for uniqueness
notificationIdinInt = notificationIdinInt + 1;
CommonUtilities.saveValueToPreference(context, Global.NOTIFICATION_ID, notificationIdinInt + "");
//Above "CommonUtilities.saveValueToPreference" is the method created by me to save new value in savePreferences.
Reset notificationId
in savedPreferences
at specific range like I have did it at 1000. So it will not create any issues in future.
Let me know if you need more detail information or any query. :)
You can set the default search_path
at the database level:
ALTER DATABASE <database_name> SET search_path TO schema1,schema2;
Or at the user or role level:
ALTER ROLE <role_name> SET search_path TO schema1,schema2;
Or if you have a common default schema in all your databases you could set the system-wide default in the config file with the search_path option.
When a database is created it is created by default from a hidden "template" database named template1, you could alter that database to specify a new default search path for all databases created in the future. You could also create another template database and use CREATE DATABASE <database_name> TEMPLATE <template_name>
to create your databases.
after your pc connects to other pc use these 4 step:
4 steps:
1- Edit this file: httpd.conf
for that click on wamp server and select Apache and select httpd.conf
2- Find this text: Deny from all
in the below tag:
<Directory "c:/wamp/www"><!-- maybe other url-->
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# AllowOverride FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
# Require all granted
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
</Directory>
3- Change to: Deny from none
like this:
<Directory "c:/wamp/www">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# AllowOverride FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
# Require all granted
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from none
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
4- Restart Apache
Don't forget restart Apache or all servises!!!
It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.
Anyhow, with that in mind, this should do it:
<form id='myform' action='jquery.php' method='GET'>
<input type='submit' id='btn1' value='Normal Submit'>
<input type='button' id='btn2' value='New Window'>
</form>
With this javascript:
var form = document.getElementById('myform');
form.onsubmit = function() {
form.target = '_self';
};
document.getElementById('btn2').onclick = function() {
form.target = '_blank';
form.submit();
}
Approaches that bind code to the submit button's click event will not work on IE.
replace Range("A1") = "Asdf" with Range("A1").value = "Asdf"
Advanced MS-DOS by Ray Duncan.
I think you are confused about how the compiler puts things together. When you use -c
flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o
files thus don't mix with -c
, and compiler warns you about that. Symbols from object file are not moved to other object files like that.
All object files should be on the final linker invocation, which is not the case here, so linker (called via g++
front-end) complains about missing symbols.
Here's a small example (calling g++
explicitly for clarity):
PROG ?= myprog
OBJS = worker.o main.o
all: $(PROG)
.cpp.o:
g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<
$(PROG): $(OBJS)
g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)
There's also makedepend
utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M
gcc
option for building make
rules.
Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.
If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.
For more info on these techniques, please click here to refer the article
Good afternoon, you could always use a little LINQ to get the selected list items and then do what you want with the results:
var selected = CBLGold.Items.Cast<ListItem>().Where(x => x.Selected);
// work with selected...
Here's a very simple example for swift Classes ONLY, and not for structures or enumerations. Note that the protocol method being optional, has two levels of optional chaining at play. Also the class adopting the protocol needs the @objc attribute in its declaration.
@objc protocol CollectionOfDataDelegate{
optional func indexDidChange(index: Int)
}
@objc class RootView: CollectionOfDataDelegate{
var data = CollectionOfData()
init(){
data.delegate = self
data.indexIsNow()
}
func indexDidChange(index: Int) {
println("The index is currently: \(index)")
}
}
class CollectionOfData{
var index : Int?
weak var delegate : CollectionOfDataDelegate?
func indexIsNow(){
index = 23
delegate?.indexDidChange?(index!)
}
}
The recommended way to style the Toolbar for a Light.DarkActionBar
clone would be to use Theme.AppCompat.Light.DarkActionbar
as parent/app theme and add the following attributes to the style to hide the default ActionBar:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
Then use the following as your Toolbar:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
For further modifications, you would create styles extending ThemeOverlay.AppCompat.Dark.ActionBar
and ThemeOverlay.AppCompat.Light
replacing the ones within AppBarLayout->android:theme
and Toolbar->app:popupTheme
. Also note that this will pick up your ?attr/colorPrimary
if you have set it in your main style so you might get a different background color.
You will find a good example of this is in the current project template with an Empty Activity
of Android Studio (1.4+).
There are many ways. Here are at least five:
/*
* An example of converting std::string to (const)char* using five
* different methods. Error checking is emitted for simplicity.
*
* Compile and run example (using gcc on Unix-like systems):
*
* $ g++ -Wall -pedantic -o test ./test.cpp
* $ ./test
* Original string (0x7fe3294039f8): hello
* s1 (0x7fe3294039f8): hello
* s2 (0x7fff5dce3a10): hello
* s3 (0x7fe3294000e0): hello
* s4 (0x7fe329403a00): hello
* s5 (0x7fe329403a10): hello
*/
#include <alloca.h>
#include <string>
#include <cstring>
int main()
{
std::string s0;
const char *s1;
char *s2;
char *s3;
char *s4;
char *s5;
// This is the initial C++ string.
s0 = "hello";
// Method #1: Just use "c_str()" method to obtain a pointer to a
// null-terminated C string stored in std::string object.
// Be careful though because when `s0` goes out of scope, s1 points
// to a non-valid memory.
s1 = s0.c_str();
// Method #2: Allocate memory on stack and copy the contents of the
// original string. Keep in mind that once a current function returns,
// the memory is invalidated.
s2 = (char *)alloca(s0.size() + 1);
memcpy(s2, s0.c_str(), s0.size() + 1);
// Method #3: Allocate memory dynamically and copy the content of the
// original string. The memory will be valid until you explicitly
// release it using "free". Forgetting to release it results in memory
// leak.
s3 = (char *)malloc(s0.size() + 1);
memcpy(s3, s0.c_str(), s0.size() + 1);
// Method #4: Same as method #3, but using C++ new/delete operators.
s4 = new char[s0.size() + 1];
memcpy(s4, s0.c_str(), s0.size() + 1);
// Method #5: Same as 3 but a bit less efficient..
s5 = strdup(s0.c_str());
// Print those strings.
printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
printf("s1 (%p): %s\n", s1, s1);
printf("s2 (%p): %s\n", s2, s2);
printf("s3 (%p): %s\n", s3, s3);
printf("s4 (%p): %s\n", s4, s4);
printf("s5 (%p): %s\n", s5, s5);
// Release memory...
free(s3);
delete [] s4;
free(s5);
}
@synthesize will generate getter and setter methods for your property. @dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass or will be provided at runtime).
Uses for @dynamic are e.g. with subclasses of NSManagedObject
(CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet.
@dynamic also can be used to delegate the responsibility of implementing the accessors. If you implement the accessors yourself within the class then you normally do not use @dynamic.
Super class:
@property (nonatomic, retain) NSButton *someButton;
...
@synthesize someButton;
Subclass:
@property (nonatomic, retain) IBOutlet NSButton *someButton;
...
@dynamic someButton;
One possible solution is:
<h:panelGroup rendered="#{bean.row == 10}">
<div class="text-success">
<h:outputText value="#{bean.row}"/>
</div>
</h:panelGroup>
cd
to the repository then
find . -name ".git*" -exec rm -R {} \;
Make sure not to accidentally pipe a single dot, slash, asterisk, or other regex wildcard into find, or else rm
will happily delete it.
Try serialize()
. It converts an array into a string format, you can then use unserialize()
to convert it back to an array. Scripts like WordPress use this to save multiple values to a single database field.
You can also use json_encode()
as Rob said, which maybe useful if you want to read the cookie in javascript.
If I want to edit a specified comment, how to get its content and its question?
You can query by sub-document: db.question.find({'comments.content' : 'xxx'})
.
This will return the whole Question document. To edit the specified comment, you then have to find the comment on the client, make the edit and save that back to the DB.
In general, if your document contains an array of objects, you'll find that those sub-objects will need to be modified client side.
Please try this in your linear layout
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
Here is the simple example which you can use for initial learning:
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
public class PQExample {
public static void main(String[] args) {
//PriorityQueue with Comparator
Queue<Customer> cpq = new PriorityQueue<>(7, idComp);
addToQueue(cpq);
pollFromQueue(cpq);
}
public static Comparator<Customer> idComp = new Comparator<Customer>(){
@Override
public int compare(Customer o1, Customer o2) {
return (int) (o1.getId() - o2.getId());
}
};
//utility method to add random data to Queue
private static void addToQueue(Queue<Customer> cq){
Random rand = new Random();
for(int i=0;i<7;i++){
int id = rand.nextInt(100);
cq.add(new Customer(id, "KV"+id));
}
}
private static void pollFromQueue(Queue<Customer> cq){
while(true){
Customer c = cq.poll();
if(c == null) break;
System.out.println("Customer Polled : "+c.getId() + " "+ c.getName());
}
}
}
JaQu is the LINQ equivalent for Java. Although it was developed for the H2 database, it should work for any database since it uses JDBC.
using ".intValue()" on BigDecimal object is not right when you want to check if its grater than zero. The only option left is ".compareTo()" method.
The default way to detach from an interactive container is Ctrl+P Ctrl+Q, but you can override it when running a new container or attaching to existing container using the --detach-keys flag.
A work-around is to use @tvanfosson's answer (the selected answer) and use JQuery (or Javascript) to set the option's value to 0:
$(document).ready(function () {
$('#DropDownListId option:first').val('0');
});
Hope this helps.
To only find the first locations, use lapply()
with min()
:
my_string <- c("test1", "test1test1", "test1test1test1")
unlist(lapply(gregexpr(pattern = '1', my_string), min))
#> [1] 5 5 5
# or the readable tidyverse form
my_string %>%
gregexpr(pattern = '1') %>%
lapply(min) %>%
unlist()
#> [1] 5 5 5
To only find the last locations, use lapply()
with max()
:
unlist(lapply(gregexpr(pattern = '1', my_string), max))
#> [1] 5 10 15
# or the readable tidyverse form
my_string %>%
gregexpr(pattern = '1') %>%
lapply(max) %>%
unlist()
#> [1] 5 10 15
Use this cmd to display the packages in your device (for windows users)
adb shell pm list packages
then you can delete completely the package with the following cmd
adb uninstall com.example.myapp
The precedent answers show you how to handle bit checks, but more often then not, it is all about flags encoded in an integer, which is not well defined in any of the precedent cases.
In a typical scenario, flags are defined as integers themselves, with a bit to 1 for the specific bit it refers to. In the example hereafter, you can check if the integer has ANY flag from a list of flags (multiple error flags concatenated) or if EVERY flag is in the integer (multiple success flags concatenated).
Following an example of how to handle flags in an integer.
Live example available here: https://rextester.com/XIKE82408
//g++ 7.4.0
#include <iostream>
#include <stdint.h>
inline bool any_flag_present(unsigned int value, unsigned int flags) {
return bool(value & flags);
}
inline bool all_flags_present(unsigned int value, unsigned int flags) {
return (value & flags) == flags;
}
enum: unsigned int {
ERROR_1 = 1U,
ERROR_2 = 2U, // or 0b10
ERROR_3 = 4U, // or 0b100
SUCCESS_1 = 8U,
SUCCESS_2 = 16U,
OTHER_FLAG = 32U,
};
int main(void)
{
unsigned int value = 0b101011; // ERROR_1, ERROR_2, SUCCESS_1, OTHER_FLAG
unsigned int all_error_flags = ERROR_1 | ERROR_2 | ERROR_3;
unsigned int all_success_flags = SUCCESS_1 | SUCCESS_2;
std::cout << "Was there at least one error: " << any_flag_present(value, all_error_flags) << std::endl;
std::cout << "Are all success flags enabled: " << all_flags_present(value, all_success_flags) << std::endl;
std::cout << "Is the other flag enabled with eror 1: " << all_flags_present(value, ERROR_1 | OTHER_FLAG) << std::endl;
return 0;
}
Another option is it to have the script set itself as the process group leader, and trap a killpg on your process group on exit.
Create a service NumberValidatorsService and add validator functions:
import { Injectable } from '@angular/core';
import { FormControl, ValidatorFn } from '@angular/forms';
@Injectable()
export class NumberValidatorsService {
constructor() { }
static max(max: number): ValidatorFn {
return (control: FormControl): { [key: string]: boolean } | null => {
let val: number = control.value;
if (control.pristine || control.pristine) {
return null;
}
if (val <= max) {
return null;
}
return { 'max': true };
}
}
static min(min: number): ValidatorFn {
return (control: FormControl): { [key: string]: boolean } | null => {
let val: number = control.value;
if (control.pristine || control.pristine) {
return null;
}
if (val >= min) {
return null;
}
return { 'min': true };
}
}
}
Import service into module.
Add includes statement in component where it is to be used:
import { NumberValidatorsService } from "app/common/number-validators.service";
Add validators to form builder:
this.myForm = this.fb.group({
numberInputName: [0, [Validators.required, NumberValidatorsService.max(100), NumberValidatorsService.min(0)]],
});
In the template, you can display the errors as follows:
<span *ngIf="myForm.get('numberInputName').errors.max">
numberInputName cannot be more than 100.
</span>
find
will find all files that match a pattern:
find . -name "*foo"
However, if you want a picture:
tree -P "*foo"
Hope this helps!
It is changed to : from PIL.Image import core as image
for new versions.
EDIT: This is now part of MoreLINQ.
What you need is a "distinct-by" effectively. I don't believe it's part of LINQ as it stands, although it's fairly easy to write:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
So to find the distinct values using just the Id
property, you could use:
var query = people.DistinctBy(p => p.Id);
And to use multiple properties, you can use anonymous types, which implement equality appropriately:
var query = people.DistinctBy(p => new { p.Id, p.Name });
Untested, but it should work (and it now at least compiles).
It assumes the default comparer for the keys though - if you want to pass in an equality comparer, just pass it on to the HashSet
constructor.
For those using newer versions Chart.js, you can set a label by setting the callback for tooltips.callbacks.label in options.
Example of this would be:
var chartOptions = {
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
return 'label';
}
}
}
}
Put them in brackets []
:
var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
It appears that IntelliJ 11 has changed the method, and the checked answer no longer works for me. In case anyone else arrives here via a search engine, here's how I solved it in IntelliJ 11:
Note that step 5 seems to be the key difference. If you select "jar directory" it will look exactly the same in the IDE but won't include the path at runtime. There appears to be no way to determine whether you've previously selected "classes" or "jar directory" after the fact.
If I recall correctly, gcc determines the filetype from the suffix. So, make it foo.cc and it should work.
And, to answer your other question, that is the difference between "gcc" and "g++". gcc is a frontend that chooses the correct compiler.
With socket.emit you can register custom event like that:
server:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
client:
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
Socket.send does the same, but you don't register to 'news' but to message:
server:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.send('hi');
});
client:
var socket = io.connect('http://localhost');
socket.on('message', function (message) {
console.log(message);
});
would be better if someone can use similar features as in libmagic on linux, as that is what I guess a better way to detect types of files than relaying on the extension name of a file.
For example, if I rename a file from mypicture.jpg to mypicture.txt On linux, it will still be reported as a picture But using this methodology here, it will be reported as text file.
Regards Tomas
just go to data directory in my case path is "wamp\bin\mysql\mysql5.6.17\data" here you will see all databases folder just delete this your database folder the db will automatically drooped :)
pep8 was recently added to PyPi.
It is now super easy to check your code against pep8.
I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.
If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%
. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE
echo %WORKSPACE%
If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!
. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion
to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &
, &&
, or ||
are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.
setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
set WORKSPACE=AFTER
echo Normal Expansion = %WORKSPACE%
echo Delayed Expansion = !WORKSPACE!
)
The output of the above is
Normal Expansion = BEFORE
Delayed Expansion = AFTER
Use HELP SET
or SET /?
from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.
Put this on an event
$(function(){
$('.package').click(function(){
var content = $('.container').html();
$(this).html(content);
});
});
Use itertools.chain:
itertools.chain(*iterables)
:Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.
from itertools import chain
A = [[1,2], [3,4]]
print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))
The output is:
[1, 2, 3, 4]
[1, 2, 3, 4]
I have the same issue as you did. I think the problem is that you used relative import in in-package import
. There is no __init__.py
in your directory. So just import as Moses answered above.
The core issue I think is when you import with a dot:
from .p_02_paying_debt_off_in_a_year import compute_balance_after
It is equivalent to:
from __main__.p_02_paying_debt_off_in_a_year import compute_balance_after
where __main__
refers to your current module p_03_using_bisection_search.py
.
Briefly, the interpreter does not know your directory architecture.
When the interpreter get in p_03.py
, the script equals:
from p_03_using_bisection_search.p_02_paying_debt_off_in_a_year import compute_balance_after
and p_03_using_bisection_search
does not contain any modules or instances called p_02_paying_debt_off_in_a_year
.
So I came up with a cleaner solution without changing python environment valuables (after looking up how requests do in relative import):
The main architecture of the directory is:
main.py
setup.py
problem_set_02/
__init__.py
p01.py
p02.py
p03.py
Then write in __init__.py
:
from .p_02_paying_debt_off_in_a_year import compute_balance_after
Here __main__
is __init__
, it exactly refers to the module problem_set_02
.
Then go to main.py
:
import problem_set_02
You can also write a setup.py
to add specific module to the environment.
For this specific problem, something like this would work:
$ sed 's/^ *//g' < input.txt > output.txt
It says to replace all spaces at the start of a line with nothing. If you also want to remove tabs, change it to this:
$ sed 's/^[ \t]+//g' < input.txt > output.txt
The leading "s" before the / means "substitute". The /'s are the delimiters for the patterns. The data between the first two /'s are the pattern to match, and the data between the second and third / is the data to replace it with. In this case you're replacing it with nothing. The "g" after the final slash means to do it "globally", ie: over the entire file rather than on only the first match it finds.
Finally, instead of < input.txt > output.txt
you can use the -i
option which means to edit the file "in place". Meaning, you don't need to create a second file to contain your result. If you use this option you will lose your original file.