Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
Go for the full installation of Git for windows (with Unix tool), and bison
and flex
would come with it in the bin
folder.
With reference to the answer provided by @Benno: Instead of changing to a specific theme, you can simply choose 'DeviceDefault' from the theme menu. This should choose the theme most compatible with the emulated device.
The each
function iterates over an array, calling the supplied function once per element, and setting this
to the active element. This:
function countdown() {
alert(this + "..");
}
$([5, 4, 3, 2, 1]).each(countdown);
will alert 5..
then 4..
then 3..
then 2..
then 1..
Map on the other hand takes an array, and returns a new array with each element changed by the function. This:
function squared() {
return this * this;
}
var s = $([5, 4, 3, 2, 1]).map(squared);
would result in s being [25, 16, 9, 4, 1]
.
Just echo your content after sending the header.
header('HTTP/1.0 403 Forbidden');
echo 'You are forbidden!';
You can have a look here. I have the detailed process described with images, right from creating the certificate, to app key to provisioning profile, to eventually the pem. http://docs.moengage.com/docs/apns-certificate-pem-file
Using ScrollView
is not very difficult. You can just add one to your layout and put whatever you want to scroll inside. ScrollView
only takes one child so if you want to put a few things inside then you should make the first thing be something like a LinearLayout
.
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- things to scroll -->
</LinearLayout>
</ScrollView>
If you want to scroll things horizontally, then use a HorizontalScrollView
.
As is talked about in this post, sometimes you want the ScrollView
content to fill the screen. For example, if you had some buttons at the end of a readme. You want the buttons to always be at the end of the text and at bottom of the screen, even if the text doesn't scroll.
If the content scrolls, everything is fine. However, if the content is smaller than the size of the screen, the buttons are not at the bottom.
This can be solved with a combination of using fillViewPort
on the ScrollView
and using a layout weight on the content. Using fillViewPort
makes the ScrollView
fill the parent area. Setting the layout_weight
on one of the views in the LinearLayout
makes that view expand to fill any extra space.
Here is the XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"> <--- fillViewport
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textview"
android:layout_height="0dp" <---
android:layout_weight="1" <--- set layout_weight
android:layout_width="match_parent"
android:padding="6dp"
android:text="hello"/>
<LinearLayout
android:layout_height="wrap_content" <--- wrap_content
android:layout_width="match_parent"
android:background="@android:drawable/bottom_bar"
android:gravity="center_vertical">
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Accept" />
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Refuse" />
</LinearLayout>
</LinearLayout>
</ScrollView>
The idea for this answer came from a previous answer that is now deleted (link for 10K users). The content of this answer is an update and adaptation of this post.
You may also do bool b = std::ifstream('filename').good();
. Without the branch instructions(like if) it must perform faster as it needs to be called thousands of times.
If you want not to type class name twice during instantiation like in:
new SomeContainer<SomeType>(SomeType.class);
You can use factory method:
<E> SomeContainer<E> createContainer(Class<E> class);
Like in:
public class Container<E> {
public static <E> Container<E> create(Class<E> c) {
return new Container<E>(c);
}
Class<E> c;
public Container(Class<E> c) {
super();
this.c = c;
}
public E createInstance()
throws InstantiationException,
IllegalAccessException {
return c.newInstance();
}
}
You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL
cmsjr had the right solution. I just wanted to point out a couple of things for your future trigger development. If you are using the values statement in an insert in a trigger, there is a stong possibility that you are doing the wrong thing. Triggers fire once for each batch of records inserted, deleted, or updated. So if ten records were inserted in one batch, then the trigger fires once. If you are refering to the data in the inserted or deleted and using variables and the values clause then you are only going to get the data for one of those records. This causes data integrity problems. You can fix this by using a set-based insert as cmsjr shows above or by using a cursor. Don't ever choose the cursor path. A cursor in a trigger is a problem waiting to happen as they are slow and may well lock up your table for hours. I removed a cursor from a trigger once and improved an import process from 40 minutes to 45 seconds.
You may think nobody is ever going to add multiple records, but it happens more frequently than most non-database people realize. Don't write a trigger that will not work under all the possible insert, update, delete conditions. Nobody is going to use the one record at a time method when they have to import 1,000,000 sales target records from a new customer or update all the prices by 10% or delete all the records from a vendor whose products you don't sell anymore.
There is a way of doing this with tags, which allows for multiple defaults.
Assume you have the following struct, with 2 default tags default0 and default1.
type A struct {
I int `default0:"3" default1:"42"`
S string `default0:"Some String..." default1:"Some Other String..."`
}
Now it's possible to Set the defaults.
func main() {
ptr := &A{}
Set(ptr, "default0")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=3 ptr.S=Some String...
Set(ptr, "default1")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=42 ptr.S=Some Other String...
}
Here's the complete program in a playground.
If you're interested in a more complex example, say with slices and maps, then, take a look at creasty/defaultse
sp_spaceused gives you the size of all the indexes combined.
If you want the size of each index for a table, use one of these two queries:
SELECT
i.name AS IndexName,
SUM(s.used_page_count) * 8 AS IndexSizeKB
FROM sys.dm_db_partition_stats AS s
JOIN sys.indexes AS i
ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id
WHERE s.[object_id] = object_id('dbo.TableName')
GROUP BY i.name
ORDER BY i.name
SELECT
i.name AS IndexName,
SUM(page_count * 8) AS IndexSizeKB
FROM sys.dm_db_index_physical_stats(
db_id(), object_id('dbo.TableName'), NULL, NULL, 'DETAILED') AS s
JOIN sys.indexes AS i
ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id
GROUP BY i.name
ORDER BY i.name
The results are usually slightly different but within 1%.
Try this:
if (!emailRegistration.matches("[a-zA-Z0-9._-]+@[a-z]+\.[a-z]+")) {
editTextEmail.setError("Invalid Email Address");
}
when you decompile and change the code you have to go on the root folder of your eclipse project and check your class in bin folder wich is on the same level as src. then open you original jar with zip tool ( 7zip is good for that ) and put the modified class in tha same package inside the jar.
When you use lazy load you need to delete your component's module and routing module from app module. If you don't, it'll try to load them when app started and throws that error.
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
AppRoutingModule,
// YourComponentModule,
// YourComponentRoutingModule
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
PYTHONPATH
is an environment variable those content is added to the sys.path
where Python looks for modules. You can set it to whatever you like.
However, do not mess with PYTHONPATH
. More often than not, you are doing it wrong and it will only bring you trouble in the long run. For example, virtual environments could do strange things…
I would suggest you learned how to package a Python module properly, maybe using this easy setup. If you are especially lazy, you could use cookiecutter to do all the hard work for you.
Maybe, you can use the array syntax of javascript :
var finalObj =[json1 , json2]
Yep, but you have to put the array first in the expression:
... | where { @("user1","user2") -notlike $_.username }
-Oisin
All the previous answers have an always-active mousemove handler. If the handler is jQuery, the additional processing jQuery performs can add up. Especially if the user is using a gaming mouse, as many as 500 events per second can occur.
This solution avoids handling every mousemove event. This result in a small timing error, but which you can adjust to your need.
function setIdleTimeout(millis, onIdle, onUnidle) {
var timeout = 0;
startTimer();
function startTimer() {
timeout = setTimeout(onExpires, millis);
document.addEventListener("mousemove", onActivity);
document.addEventListener("keydown", onActivity);
}
function onExpires() {
timeout = 0;
onIdle();
}
function onActivity() {
if (timeout) clearTimeout(timeout);
else onUnidle();
//since the mouse is moving, we turn off our event hooks for 1 second
document.removeEventListener("mousemove", onActivity);
document.removeEventListener("keydown", onActivity);
setTimeout(startTimer, 1000);
}
}
To change database owner:
ALTER AUTHORIZATION ON DATABASE::YourDatabaseName TO sa
As of SQL Server 2014 you can still use sp_changedbowner
as well, even though Microsoft promised to remove it in the "future" version after SQL Server 2012. They removed it from SQL Server 2014 BOL though.
Some Improvements in Sudheesh B Nair's answer, i have noticed it will wait for handler even while pressing back twice immediately, so cancel handler as shown below. I have cancled toast also to prevent it to display after app exit.
boolean doubleBackToExitPressedOnce = false;
Handler myHandler;
Runnable myRunnable;
Toast myToast;
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
myHandler.removeCallbacks(myRunnable);
myToast.cancel();
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
myToast = Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT);
myToast.show();
myHandler = new Handler();
myRunnable = new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
};
myHandler.postDelayed(myRunnable, 2000);
}
I found the solution as Its problem with Android Studio 3.1 Canary 6
My backup of Android Studio 3.1 Canary 5 is useful to me and saved my half day.
Now My build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion '27.0.2'
defaultConfig {
applicationId "com.example.demo"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
dataBinding {
enabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:recyclerview-v7:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:cardview-v7:${rootProject.ext.supportLibVersion}"
implementation "com.squareup.retrofit2:retrofit:2.3.0"
implementation "com.google.code.gson:gson:2.8.2"
implementation "com.android.support.constraint:constraint-layout:1.0.2"
implementation "com.squareup.retrofit2:converter-gson:2.3.0"
implementation "com.squareup.okhttp3:logging-interceptor:3.6.0"
implementation "com.squareup.picasso:picasso:2.5.2"
implementation "com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3"
compile 'com.github.elevenetc:badgeview:v1.0.0'
annotationProcessor 'com.github.elevenetc:badgeview:v1.0.0'
testImplementation "junit:junit:4.12"
androidTestImplementation("com.android.support.test.espresso:espresso-core:3.0.1", {
exclude group: "com.android.support", module: "support-annotations"
})
}
and My gradle is:
classpath 'com.android.tools.build:gradle:3.1.0-alpha06'
and its working finally.
I think there problem in Android Studio 3.1 Canary 6
Thank you all for your time.
Just use.
<![CDATA[ your text here ]]>
This will allow any characters except the ending
]]>
So you can include characters that would be illegal such as & and >. For example.
<element><![CDATA[ characters such as & and > are allowed ]]></element>
However, attributes will need to be escaped as CDATA blocks can not be used for them.
How about this? There's no need for key codes (at least in Lion, not sure about earlier), and a subroutine simplifies the main script.
The below script will ssh to localhost as user "me", enter password "myPassw0rd" after a 1 second delay, issue ls, delay 2 seconds, and then exit.
tell application "Terminal"
activate
my execCmd("ssh me@localhost", 1)
my execCmd("myPassw0rd", 0)
my execCmd("ls", 2)
my execCmd("exit", 0)
end tell
on execCmd(cmd, pause)
tell application "System Events"
tell application process "Terminal"
set frontmost to true
keystroke cmd
keystroke return
end tell
end tell
delay pause
end execCmd
This is the file we're all looking for (inside your Eclipse workspace):
.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.ui.prefs
You will find an @author tag with the name you want to change. Restart Eclipse and it will work.
For accents you have to use the Unicode format (e.g. '\u00E1' for á).
You can also modify the 'ini' file as prior answers suggest or set the user name var for a global solution. Or override the @author tag in the Preferences menu for a local solution. Those are both valid solutions to this problem.
But if you're looking for 'that' author name that is bothering most of us, is in that file.
The best solution is just not to use anonymous classes.
public class Test
{
class DummyInterfaceImplementor : IDummyInterface
{
public string A { get; set; }
public string B { get; set; }
}
public void WillThisWork()
{
var source = new DummySource[0];
var values = from value in source
select new DummyInterfaceImplementor()
{
A = value.A,
B = value.C + "_" + value.D
};
DoSomethingWithDummyInterface(values.Cast<IDummyInterface>());
}
public void DoSomethingWithDummyInterface(IEnumerable<IDummyInterface> values)
{
foreach (var value in values)
{
Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);
}
}
}
Note that you need to cast the result of the query to the type of the interface. There might be a better way to do it, but I couldn't find it.
I stopped using DECODE
several years ago because it is non-portable. Also, it is less flexible and less readable than a CASE/WHEN
.
However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.
select a, b, decode(a, b, 'true', 'false') as same
from t;
A B SAME
------ ------ -----
1 1 true
1 0 false
1 false
null null true
Something the other answers are missing is that it must be understood that Authentication and Authorization in the context of RFC 2616 refers ONLY to the HTTP Authentication protocol of RFC 2617. Authentication by schemes outside of RFC2617 is not supported in HTTP status codes and are not considered when deciding whether to use 401 or 403.
Unauthorized indicates that the client is not RFC2617 authenticated and the server is initiating the authentication process. Forbidden indicates either that the client is RFC2617 authenticated and does not have authorization or that the server does not support RFC2617 for the requested resource.
Meaning if you have your own roll-your-own login process and never use HTTP Authentication, 403 is always the proper response and 401 should never be used.
From RFC2616
10.4.2 401 Unauthorized
The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8).
and
10.4.4 403 Forbidden The server understood the request but is refusing to fulfil it. Authorization will not help and the request SHOULD NOT be repeated.
The first thing to keep in mind is that "Authentication" and "Authorization" in the context of this document refer specifically to the HTTP Authentication protocols from RFC 2617. They do not refer to any roll-your-own authentication protocols you may have created using login pages, etc. I will use "login" to refer to authentication and authorization by methods other than RFC2617
So the real difference is not what the problem is or even if there is a solution. The difference is what the server expects the client to do next.
401 indicates that the resource can not be provided, but the server is REQUESTING that the client log in through HTTP Authentication and has sent reply headers to initiate the process. Possibly there are authorizations that will permit access to the resource, possibly there are not, but let's give it a try and see what happens.
403 indicates that the resource can not be provided and there is, for the current user, no way to solve this through RFC2617 and no point in trying. This may be because it is known that no level of authentication is sufficient (for instance because of an IP blacklist), but it may be because the user is already authenticated and does not have authority. The RFC2617 model is one-user, one-credentials so the case where the user may have a second set of credentials that could be authorized may be ignored. It neither suggests nor implies that some sort of login page or other non-RFC2617 authentication protocol may or may not help - that is outside the RFC2616 standards and definition.
Why not just:
$('#b').click(function () {
var val = $(this).val();
})
Or if you don't click it (and I guess you won't) and you will use submit button, you can use prev()
function either.
I think this code is short and clear:
int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
Is that what you were looking for?
tl;dr (new Date('6/29/2011 4:52:48 PM UTC')).toString()
The source string must specify a time zone or UTC.
One-liner:
(new Date('6/29/2011 4:52:48 PM UTC')).toString()
Result in one of my web browsers:
"Wed Jun 29 2011 09:52:48 GMT-0700 (Pacific Daylight Time)"
This approach even selects standard/daylight time appropriately.
(new Date('1/29/2011 4:52:48 PM UTC')).toString()
Result in my browser:
"Sat Jan 29 2011 08:52:48 GMT-0800 (Pacific Standard Time)"
Did you try list(x)??
y = '+123-456-7890'
c =list(y)
c
['+', '1', '2', '3', '-', '4', '5', '6', '-', '7', '8', '9', '0']
My problem was that I was looking at it from the long angle:
function new_line() {
var html= '<div><br><input type="text" value="" id="dateP_'+ i +'"></div>';
document.getElementById("container").innerHTML += html;
$('#dateP_'+i).datepicker({
showOn: 'button',
buttonImage: 'calendar.gif',
buttonImageOnly: true
});
i++;
}
Android Studio is based on IntelliJ, and it comes with support for SVN (along with git and mercurial) bundled in. Check http://www.jetbrains.com/idea/features/version_control.html for more info.
I found another solution here, since I ran into both post...
This is from the Myles answer:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListBox.ItemContainerStyle>
This worked for me.
Try this:
import base64
imgdata = base64.b64decode(imgstring)
filename = 'some_image.jpg' # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
f.write(imgdata)
# f gets closed when you exit the with statement
# Now save the value of filename to your database
Download the server response as an array buffer. Store it as a Blob using the content type from the server (which should be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
):
var httpPromise = this.$http.post(server, postData, { responseType: 'arraybuffer' });
httpPromise.then(response => this.save(new Blob([response.data],
{ type: response.headers('Content-Type') }), fileName));
Save the blob to the user's device:
save(blob, fileName) {
if (window.navigator.msSaveOrOpenBlob) { // For IE:
navigator.msSaveBlob(blob, fileName);
} else { // For other browsers:
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
}
}
Make the left and right margins of your UL auto and assign it a width:
#headermenu ul {
margin: 0 auto;
width: 620px;
}
Edit: As kleinfreund has suggested, you can also center align the container and give the ul an inline-block display, but you then also have to give the LIs either a left float or an inline display.
#headermenu {
text-align: center;
}
#headermenu ul {
display: inline-block;
}
#headermenu ul li {
float: left; /* or display: inline; */
}
If you have installed Batarang
Then you can just write:
$scope
when you have the element selected in the elements view in chrome. Ref - https://github.com/angular/angularjs-batarang#console
"I tried to figure out, why exactly we need Observer and Observable"
As previous answers already stated, they provide means of subscribing an observer to receive automatic notifications of an observable.
One example application where this may be useful is in data binding, let's say you have some UI that edits some data, and you want the UI to react when the data is updated, you can make your data observable, and subscribe your UI components to the data
Knockout.js is a MVVM javascript framework that has a great getting started tutorial, to see more observables in action I really recommend going through the tutorial. http://learn.knockoutjs.com/
I also found this article in Visual Studio 2008 start page (The Observer Pattern is the foundation of Model View Controller (MVC) development) http://visualstudiomagazine.com/articles/2013/08/14/the-observer-pattern-in-net.aspx
Swift 4 with customType:
let button = UIButton(frame: aRectHere)
let buttonImage = UIImage(named: "imageName")
button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
/register-form.html
to signup-form.html
./register.php
, then now load (GET) /success.html
./register.php
, then this tells it to redo the POST at /signup.php
.RFC 7231 (from 2014) is very readable and not overly verbose. If you want to know the exact answer, it's a recommended read. Some other answers use RFC 2616 from 1999, but nothing changed.
RFC 7238 specifies the 308 status. It is considered experimental, but it was already supported by all major browsers in 2016.
You could copy down a formula like the following in a new column...
=IF(ISNUMBER(FIND("-",A1)),1,0)
... then sort on that column, highlight all the rows where the value is 1 and delete them.
As a follow up to @ubik's answer, here are the three simple (one-time) steps to get the 'subl' command working on your remote server:
rsub
package in Sublime Text using the Sublime Package Manager[Local] Execute the following Bash command (this will set up an SSH tunnel, which is rsub's secret sauce):
printf "Host *\n RemoteForward 52698 127.0.0.1:52698" >> ~/.ssh/config
[Server] Execute the following Bash command on your remote server (this will install the 'subl' shell command):
sudo wget -O /usr/local/bin/subl https://raw.github.com/aurora/rmate/master/rmate; sudo chmod +x /usr/local/bin/subl
And voila! You're now using Sublime Text over SSH.
You can open an example file in Sublime Text from the server with something like subl ~/test.txt
Basically, the term "x-bit machine" does not depend on your machine. That is why we do not need to change our processors or other hardware in order to migrate from a 32bit system to a 64bit one (or vice versa).
32bit and 64bit stands for the addressing capability of the OS running on your machine.
However, it still does not mean that a x-bit operating system is capable to address 2^x GB memory. Because the 'B' in "GB" means "byte" and not "bit". 1 byte equals 8 bits.
Actually a 32bit system can not even address 2^32/8 = 2^29 GB memory space while there should some memory be reserved to the OS.
It is something just below 3 GB.
What about using git branch -m to rename the master branch to another one, then rename seotweaks branch to master? Something like this:
git branch -m master old-master
git branch -m seotweaks master
git push -f origin master
This might remove commits in origin master, please check your origin master before running git push -f origin master
.
In my application which calls two services, I compared both Task.Run and Task.Factory.StartNew. I found that in my case both of them work fine. However, the second one is faster.
@RequestBody MultipartFile[] submissions
should be
@RequestParam("file") MultipartFile[] submissions
The files are not the request body, they are part of it and there is no built-in HttpMessageConverter
that can convert the request to an array of MultiPartFile
.
You can also replace HttpServletRequest
with MultipartHttpServletRequest
, which gives you access to the headers of the individual parts.
make the image float: left;
and the text float: right;
Take a look at this fiddle I used a picture online but you can just swap it out for your picture.
Update django-geoposition at least to version 0.2.3 and add this to settings.py:
GEOPOSITION_GOOGLE_MAPS_API_KEY = 'YOUR_API_KEY'
That code transforms any bootstrap table row that has data-href
attribute set into a clickable element
Note: data-href
attribute is a valid tr
attribute (HTML5), href
attributes on tr element are not.
$(function(){
$('.table tr[data-href]').each(function(){
$(this).css('cursor','pointer').hover(
function(){
$(this).addClass('active');
},
function(){
$(this).removeClass('active');
}).click( function(){
document.location = $(this).attr('data-href');
}
);
});
});
byte[] iso88591Data = theString.getBytes("ISO-8859-1");
Will do the trick. From your description it seems as if you're trying to "store an ISO-8859-1 String". String objects in Java are always implicitly encoded in UTF-16. There's no way to change that encoding.
What you can do, 'though is to get the bytes that constitute some other encoding of it (using the .getBytes()
method as shown above).
Shortly you can not instantiate the static class: Ex:
static class myStaticClass
{
public static void someFunction()
{ /* */ }
}
You can not make like this:
myStaticClass msc = new myStaticClass(); // it will cause an error
You can make only:
myStaticClass.someFunction();
You could simplify this a lot:
This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:
function validatePassword()
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
return password.value !== "" && password.value === confirm_password.value;
// not empty and equal
}
Addressing an element of dictionary is like sitting on donkey and enjoy the ride.
As a rule of Python, a DICTIONARY is orderless
If there is
dic = {1: "a", 2: "aa", 3: "aaa"}
Now suppose if I go like dic[10] = "b"
, then it will not add like this always
dic = {1:"a",2:"aa",3:"aaa",10:"b"}
It may be like
dic = {1: "a", 2: "aa", 3: "aaa", 10: "b"}
Or
dic = {1: "a", 2: "aa", 10: "b", 3: "aaa"}
Or
dic = {1: "a", 10: "b", 2: "aa", 3: "aaa"}
Or any such combination.
So a rule of thumb is that a DICTIONARY is orderless!
Create activity as dialog, Here is Full Example
AndroidManife.xml
<activity android:name=".appview.settings.view.DialogActivity" android:excludeFromRecents="true" android:theme="@style/Theme.AppCompat.Dialog"/>
DialogActivity.kt
class DialogActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dialog)
this.setFinishOnTouchOutside(true)
btnOk.setOnClickListener {
finish()
}
}
}
activity_dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#0072ff"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="@dimen/_300sdp"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/txtTitle"
style="@style/normal16Style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="20dp"
android:paddingBottom="20dp"
android:text="Download"
android:textColorHint="#FFF" />
<View
android:id="@+id/viewDivider"
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#fff"
android:backgroundTint="@color/white_90"
app:layout_constraintBottom_toBottomOf="@id/txtTitle" />
<TextView
style="@style/normal14Style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="20dp"
android:paddingBottom="20dp"
android:text="Your file is download"
android:textColorHint="#FFF" />
<Button
android:id="@+id/btnOk"
style="@style/normal12Style"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginBottom="20dp"
android:background="@drawable/circle_corner_layout"
android:text="Ok"
android:textAllCaps="false" />
</LinearLayout>
</LinearLayout>
$('.login').toggle(
function(){
$('#panel').animate({
height: "150",
padding:"20px 0",
backgroundColor:'#000000',
opacity:.8
}, 500);
$('#otherdiv').animate({
//otherdiv properties here
}, 500);
},
function(){
$('#panel').animate({
height: "0",
padding:"0px 0",
opacity:.2
}, 500);
$('#otherdiv').animate({
//otherdiv properties here
}, 500);
});
I have an answer that doesn't require a UDF, XML Because IN accepts a select statement e.g. SELECT * FROM Test where Data IN (SELECT Value FROM TABLE)
You really only need a way to convert the string into a table.
This can be done with a recursive CTE, or a query with a number table (or Master..spt_value)
Here's the CTE version.
DECLARE @InputString varchar(8000) = 'ruby,rails,scruffy,rubyonrails'
SELECT @InputString = @InputString + ','
;WITH RecursiveCSV(x,y)
AS
(
SELECT
x = SUBSTRING(@InputString,0,CHARINDEX(',',@InputString,0)),
y = SUBSTRING(@InputString,CHARINDEX(',',@InputString,0)+1,LEN(@InputString))
UNION ALL
SELECT
x = SUBSTRING(y,0,CHARINDEX(',',y,0)),
y = SUBSTRING(y,CHARINDEX(',',y,0)+1,LEN(y))
FROM
RecursiveCSV
WHERE
SUBSTRING(y,CHARINDEX(',',y,0)+1,LEN(y)) <> '' OR
SUBSTRING(y,0,CHARINDEX(',',y,0)) <> ''
)
SELECT
*
FROM
Tags
WHERE
Name IN (select x FROM RecursiveCSV)
OPTION (MAXRECURSION 32767);
Center x = x + 1/2 of width
Center y = y + 1/2 of height
If you know the width and height already then you only need one set of coordinates.
Be aware, that your code is quite noisy. I know the thread is old, but a lot of people will read it anyway. You could do the same thing using the guava library with:
if ("POST".equalsIgnoreCase(request.getMethod())) {
test = CharStreams.toString(request.getReader());
}
System.getProperty("user.name") is not a good security option since that environment variable could be faked: C:\ set USERNAME="Joe Doe" java ... // will give you System.getProperty("user.name") You ought to do:
com.sun.security.auth.module.NTSystem NTSystem = new com.sun.security.auth.module.NTSystem();
System.out.println(NTSystem.getName());
JDK 1.5 and greater.
I use it within an applet, and it has to be signed. info source
Create a file named .gitignore on the root of your repository. In this file you put the relative path to each file you wish to ignore in a single line. You can use the *
wildcard.
Python lists were not made to operate on the beginning of the list and are very ineffective at this operation.
While you can write
mylist = [1, 2 ,3 ,4]
mylist.pop(0)
It's very inefficient.
If you only want to delete items from your list, you can do this with del
:
del mylist[:n]
Which is also really fast:
In [34]: %%timeit
help=range(10000)
while help:
del help[:1000]
....:
10000 loops, best of 3: 161 µs per loop
If you need to obtain elements from the beginning of the list, you should use collections.deque
by Raymond Hettinger and its popleft()
method.
from collections import deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'
A comparison:
In [30]: %%timeit
....: help=range(10000)
....: while help:
....: help.pop(0)
....:
100 loops, best of 3: 17.9 ms per loop
In [33]: %%timeit
help=deque(range(10000))
while help:
help.popleft()
....:
1000 loops, best of 3: 812 µs per loop
This could be for 2 reasons for this:
service ref is outdated, right click service ref n update it.
contract which you have implemented might be different what client has. Compare both service n client contract n fix the contracts mismatch.
There's a far more simpler solution to tackle this.
The reason why you get ValueError: Index contains duplicate entries, cannot reshape
is because, once you unstack "Location
", then the remaining index columns "id
" and "date
" combinations are no longer unique.
You can avoid this by retaining the default index column (row #) and while setting the index using "id
", "date
" and "location
", add it in "append
" mode instead of the default overwrite mode.
So use,
e.set_index(['id', 'date', 'location'], append=True)
Once this is done, your index columns will still have the default index along with the set indexes. And unstack
will work.
Let me know how it works out.
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29
I had better luck in combining Darren's answer and kyernetikos's answer.
const nameFunction = function (fn, name) {_x000D_
return Object.defineProperty(fn, 'name', {value: name, configurable: true});_x000D_
};_x000D_
_x000D_
/* __________________________________________________________________________ */_x000D_
_x000D_
let myFunc = function oldName () {};_x000D_
_x000D_
console.log(myFunc.name); // oldName_x000D_
_x000D_
myFunc = nameFunction(myFunc, 'newName');_x000D_
_x000D_
console.log(myFunc.name); // newName
_x000D_
Note: configurable
is set to true
to match the standard ES2015 spec for Function.name1
This especially helped in getting around an error in Webpack similar to this one.
Update: I was thinking of publishing this as an npm package, but this package from sindresorhus does exactly the same thing.
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
You can use the modulus operator like this, no need for jQuery. Just replace the alerts
with your code.
var x = 2;
if (x % 2 == 0)
{
alert('even');
}
else
{
alert('odd')
}
If it's sufficient to use the following criteria to locate the profile:
<key>Name</key>
<string>iOS Team Provisioning Profile: *</string>
you can scan the directory using awk. This one-liner will find the first file that contains the name starting with "iOS Team".
awk 'BEGIN{e=1;pat="<string>"tolower("iOS Team")}{cur=tolower($0);if(cur~pat &&prev~/<key>name<\/key>/){print FILENAME;e=0;exit};if($0!~/^\s*$/)prev=cur}END{exit e}' *
Here's a script that also returns the first match, but is easier to work with.
#!/bin/bash
if [ $# != 1 ] ; then
echo Usage: $0 \<start of provisioning profile name\>
exit 1
fi
read -d '' script << 'EOF'
BEGIN {
e = 1
pat = "<string>"tolower(prov)
}
{
cur = tolower($0)
if (cur ~ pat && prev ~ /<key>name<\\/key>/) {
print FILENAME
e = 0
exit
}
if ($0 !~ /^\s*$/) {
prev = cur
}
}
END {
exit e
}
EOF
awk -v "prov=$1" "$script" *
It can be called from within the profiles directory, $HOME/Library/MobileDevice/Provisioning Profiles:
~/findprov "iOS Team"
To use the script, save it to a suitable location and remember to set the executable mode; e.g., chmod ugo+x
Use the -ss
option:
ffmpeg -ss 01:23:45 -i input -vframes 1 -q:v 2 output.jpg
For JPEG output use -q:v
to control output quality. Full range is a linear scale of 1-31 where a lower value results in a higher quality. 2-5 is a good range to try.
The select filter provides an alternative method for more complex needs such as selecting only certain frame types, or 1 per 100, etc.
Placing -ss
before the input will be faster. See FFmpeg Wiki: Seeking and this excerpt from the ffmpeg
cli tool documentation:
-ss
position (input/output)When used as an input option (before
-i
), seeks in this input file to position. Note the in most formats it is not possible to seek exactly, soffmpeg
will seek to the closest seek point before position. When transcoding and-accurate_seek
is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when-noaccurate_seek
is used, it will be preserved.When used as an output option (before an output filename), decodes but discards input until the timestamps reach position.
position may be either in seconds or in
hh:mm:ss[.xxx]
form.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/csv");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 0);
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
then you just need to add the response
public void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode) {
case 0: {
//what you want to do
//file = new File(uri.getPath());
}
}
}
I used this for python 3.5. I did it using subprocess module.Using the password like this is very insecure.
The subprocess module takes command as a list of strings so either create a list beforehand using split() or pass the whole list later. Read the documentation for more information.
What we are doing here is echoing the password and then using pipe we pass it on to the sudo through '-S' argument.
#!/usr/bin/env python
import subprocess
sudo_password = 'mysecretpass'
command = 'apach2ctl restart'
command = command.split()
cmd1 = subprocess.Popen(['echo',sudo_password], stdout=subprocess.PIPE)
cmd2 = subprocess.Popen(['sudo','-S'] + command, stdin=cmd1.stdout, stdout=subprocess.PIPE)
output = cmd2.stdout.read().decode()
It is being pointed out not directly in the file which is caused the error. But it is actually triggered in a controller file. It happens when a return value from a method defined inside in a controller file is set on a boolean value. It must not be set on a boolean type but on the other hand, it must be set or given a value of a string type. It can be shown as follows :
public function saveFormSummary(Request $request) {
...
$status = true;
return $status;
}
Given the return value of a boolean type above in a method, to be able to solve the problem to handle the error specified. Just change the type of the return value into a string type
as follows :
public function saveFormSummary(Request $request) {
...
$status = "true";
return $status;
}
Here goes your code by parsing the variables in the function.
<html>
<body>
<p>Click the button to calculate x.</p>
<button onclick="myFunction()">Try it</button>
<br/>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">
<br>Enter second number:
<input type="text" id="txt2" name="text2">
<p id="demo"></p>
<script>
function myFunction() {
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = y + z;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Answer
<input type="button">
can be used anywhere, not just within form and they do not submit form if they are in one. Much better suited with Javascript
.
<input type="submit">
should be used in forms only and they will send a request (either GET or POST) to specified URL. They should not be put in any HTML place.
This is the approach I'm using and you can modify it based on your needs:
^[\w]{1,}[\w.+-]{0,}@[\w-]{2,}([.][a-zA-Z]{2,}|[.][\w-]{2,}[.][a-zA-Z]{2,})$
Explanation:
We want to make sure that the e-mail address always starts with a word:
^[\w]
A word is any character, digit or underscore. You can use [a-zA-Z0-9_] pattern, but it will give you the same result and it's longer.
Next, we want to make sure that there is at least one such character:
^[\w]{1,}
Next, we want to allow any word, digit or special characters in the name. This way, we can be sure that the e-mail won't start with the dot, but can contain the dot on other than the first position:
^[\w]{1,}[\w.+-]
And of course, there doesn't have to be any of such character because e-mail address can have only one letter followed by @:
^[\w]{1,}[\w.+-]{0,}
Next, we need the @ character which is mandatory, but there can be only one in the whole e-mail:
^[\w]{1,}[\w.+-]{0,}@
Right behind the @ character, we want the domain name. Here, you can define how many characters you want as minimum and from which range of characters. I'd go for all word characters including the hyphen [\w-] and I want at least two of them {2,}. If you want to allow domains like t.co, you would have to allow one character from this range {1,}:
^[\w]{1,}[\w.+-]{0,}@[\w-]{2,}
Next, we need to deal with two cases. Either there's just the domain name followed by the domain extension, or there's subdomain name followed by the domain name followed by the extension, for example, abc.com versus abc.co.uk. To make this work, we need to use the (a|b) token where a stands for the first case, b stands for the second case and | stands for logical OR. In the first case, we will deal with just the domain extension, but since it will be always there no matter the case, we can safely add it to both cases:
^[\w]{1,}[\w.+-]{0,}@[\w-]{2,}([.][a-zA-Z]{2,}|[.][a-zA-Z]{2,})
This pattern says that we need exactly one dot character followed by letters, no digits, and we want at least two of them, in both cases.
For the second case, we will add the domain name in front of the domain extension, thus making the original domain name a subdomain:
^[\w]{1,}[\w.+-]{0,}@[\w-]{2,}([.][a-zA-Z]{2,}|[.][\w-]{2,}[.][a-zA-Z]{2,})
The domain name can consist of word characters including the hyphen and again, we want at least two characters here.
Finally, we need to mark the end of the whole pattern:
^[\w]{1,}[\w.+-]{0,}@[\w-]{2,}([.][a-zA-Z]{2,}|[.][\w-]{2,}[.][a-zA-Z]{2,})$
Go here and test if your e-mail matches the pattern: https://regex101.com/r/374XLJ/1
An alternative way to do it is:
var div = document.getElementById('myDiv');
while(div.firstChild)
div.removeChild(div.firstChild);
However, using document.getElementById('myDiv').innerHTML = "";
is faster.
See: Benchmark test
N.B.
Both methods preserve the div.
It seens that people really dont get what Dependency injection and inversion of control means anymore.
The practice of using inversion of control is to have classes or function that depends of another classes or functions, but instead of creating the instances whithin the class of function code it is better to receive it as a parameter, so loose coupling can be archieved. That has many benefits as more testability and to archieve the liskov substitution principle.
You see, by working with interfaces and injections, your code gets more maintanable, since you can change the behavior easily, because you won't have to rewrite a single line of code (maybe a line or two on the DI configuration) of your class to change it's behavior, since the classes that implements the interface your class is waiting for can vary independently as long as they follow the interface. One of the best strategies to keep code decoupled and easy to maintain is to follow at least the single responsability, substitution and dependency inversion principles.
Whats a DI library good for if you can instantiate a object yourself inside a package and import it to inject it yourself? The chosen answer is right, since java has no procedural sections (code outside of classes), all that goes into boring configuration xml's, hence the need of a class to instantiate and inject dependencies on a lazy load fashion so you don't blow away your performance, while on python you just code the injections on the "procedural" (code outside classes) sections of your code
The Material Design Typography page has demos for some of these fonts and suggestions on choosing fonts and styles.
For code sleuths: fonts.xml
is the definitive and ever-expanding list of Android fonts.
Set the android:fontFamily
and android:textStyle
attributes, e.g.
<!-- Roboto Bold -->
<TextView
android:fontFamily="sans-serif"
android:textStyle="bold" />
to the desired values from this table:
Font | android:fontFamily | android:textStyle
-------------------------|-----------------------------|-------------------
Roboto Thin | sans-serif-thin |
Roboto Light | sans-serif-light |
Roboto Regular | sans-serif |
Roboto Bold | sans-serif | bold
Roboto Medium | sans-serif-medium |
Roboto Black | sans-serif-black |
Roboto Condensed Light | sans-serif-condensed-light |
Roboto Condensed Regular | sans-serif-condensed |
Roboto Condensed Medium | sans-serif-condensed-medium |
Roboto Condensed Bold | sans-serif-condensed | bold
Noto Serif | serif |
Noto Serif Bold | serif | bold
Droid Sans Mono | monospace |
Cutive Mono | serif-monospace |
Coming Soon | casual |
Dancing Script | cursive |
Dancing Script Bold | cursive | bold
Carrois Gothic SC | sans-serif-smallcaps |
(Noto Sans is a fallback font; you can't specify it directly)
Note: this table is derived from fonts.xml
. Each font's family name and style is listed in fonts.xml, e.g.
<family name="serif-monospace">
<font weight="400" style="normal">CutiveMono.ttf</font>
</family>
serif-monospace
is thus the font family, and normal
is the style.
Based on the log of fonts.xml and the former system_fonts.xml, you can see when each font was added:
Caveat: I'm running Ubuntu
sudo service --status-all
you can get a list of all running services by typing this command,
If you're running Tomcat as a service it will showes up as ("tomcat"), so run :
sudo service tomcat7 stop
(tomcat7 or 8 or depending to the name that you have in the list of running services )
else and if you are using apache tomcat you will see ("apache2") showing up with the list of services then run :
sudo service apache2 stop
Here's a good technique to display an overlay image that is centered with a semi-transparent background over an image link:
<div class="image-container">
<a class="link" href="#" >
<img class="image" src="/img/thumbnail.png"/>
<span class="overlay-image"><img src="/img/overlay.png"></span>
</a>
</div>
div.image-container{
position: relative;
}
a.link{
text-decoration: none;
position: relative;
display: block;
}
a.link span.overlay-image{
visibility: hidden;
position: absolute;
left: 0px;
top: 0px;
bottom: 0px;
right: 0px;
background-color: rgba(0,0,0,0.2); /* black background with 20% alpha */
}
a.link span.overlay-image:before { /* create a full-height inline block pseudo=element */
content: ' ';
display: inline-block;
vertical-align: middle; /* vertical alignment of the inline element */
height: 100%;
}
a.link:hover span.overlay-image img{
display: inline-block;
vertical-align: middle;
}
a.link:hover span.overlay-image{
visibility: visible;
}
After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:
adb shell
recovery --wipe_data
Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.
EDIT:
For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command
For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c
One issue you might run into is is_home()
returns true when a registered query_var is present in the home URL. For example, if http://example.com
displays a static page instead of the blog, http://example.com/?c=123
will return the blog.
See https://core.trac.wordpress.org/ticket/25143 and https://wordpress.org/support/topic/adding-query-var-makes-front-page-missing/ for more info on this.
What you can do (if you're not attempting to affect the query) is use add_rewrite_endpoint()
. It should be run during the init
action as it affects the rewrite rules. Eg.
add_action( 'init', 'add_custom_setcookie_rewrite_endpoints' );
function add_custom_setcookie_rewrite_endpoints() {
//add ?c=123 endpoint with
//EP_ALL so endpoint is present across all places
//no effect on the query vars
add_rewrite_endpoint( 'c', EP_ALL, $query_vars = false );
}
This should give you access to $_GET['c']
when the url contains more information like www.example.com/news?c=123
.
Remember to flush your rewrite rules after adding/modifying this.
If I get you right, you want to add the sensors
collection to the node
. If you have a mapping between both models you can either use the include
functionality explained here or the values
getter defined on every instance. You can find the docs for that here.
The latter can be used like this:
db.Sensors.findAll({
where: {
nodeid: node.nodeid
}
}).success(function (sensors) {
var nodedata = node.values;
nodedata.sensors = sensors.map(function(sensor){ return sensor.values });
// or
nodedata.sensors = sensors.map(function(sensor){ return sensor.toJSON() });
nodesensors.push(nodedata);
response.json(nodesensors);
});
There is chance that nodedata.sensors = sensors
could work as well.
FacesContext.addMessage(String, FacesMessage) requires the component's clientId, not it's id. If you're wondering why, think about having a control as a child of a dataTable, stamping out different values with the same control for each row - it would be possible to have a different message printed for each row. The id is always the same; the clientId is unique per row.
So "myform:mybutton" is the correct value, but hard-coding this is ill-advised. A lookup would create less coupling between the view and the business logic and would be an approach that works in more restrictive environments like portlets.
<f:view>
<h:form>
<h:commandButton id="mybutton" value="click"
binding="#{showMessageAction.mybutton}"
action="#{showMessageAction.validatePassword}" />
<h:message for="mybutton" />
</h:form>
</f:view>
Managed bean logic:
/** Must be request scope for binding */
public class ShowMessageAction {
private UIComponent mybutton;
private boolean isOK = false;
public String validatePassword() {
if (isOK) {
return "ok";
}
else {
// invalid
FacesMessage message = new FacesMessage("Invalid password length");
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(mybutton.getClientId(context), message);
}
return null;
}
public void setMybutton(UIComponent mybutton) {
this.mybutton = mybutton;
}
public UIComponent getMybutton() {
return mybutton;
}
}
A lot of great editors have come out since my original answer. I currently use the following text editors: Sublime Text 3 (Mac/Windows), Visual Studio Code (Mac/Windows) and Atom (Mac/Windows). I also use the following IDEs: Visual Studio 2015 (Windows/Paid & Free Versions) and Jetrbrains WebStorm (Windows/Paid, tried the demo and liked it).
My preference is using Sublime Text 3.
Microsoft Web Matrix and Dreamweaver are great.
Visual Studio and Expression Web are also great but may be overkill for you.
For just plain text editors, Sublime Text 2 is really cool
There is a way to get a range of values in a single query, but its a bit slow. It can be sped up by using cache tables.
assume you want a select with a range of all BOOLEAN values:
SELECT 0 as b UNION SELECT 1 as b;
we can make a view
CREATE VIEW ViewBoolean AS SELECT 0 as b UNION SELECT 1 as b;
then you can do a Byte by
CREATE VIEW ViewByteValues AS
SELECT b0.b + b1.b*2 + b2.b*4 + b3.b*8 + b4.b*16 + b5.b*32 + b6.b*64 + b7.b*128 as v FROM
ViewBoolean b0,ViewBoolean b1,ViewBoolean b2,ViewBoolean b3,ViewBoolean b4,ViewBoolean b5,ViewBoolean b6,ViewBoolean b7;
then you can do a
CREATE VIEW ViewInt16 AS
SELECT b0.v + b1.v*256 as v FROM
ViewByteValues b0,ViewByteValues b1;
then you can do a
SELECT v+MIN as x FROM ViewInt16 WHERE v<MAX-MIN;
To speed this up I skipped the auto-calculation of byte values and made myself a
CREATE VIEW ViewByteValues AS
SELECT 0 as v UNION SELECT 1 as v UNION SELECT ...
...
...254 as v UNION SELECT 255 as v;
If you need a range of dates you can do.
SELECT DATE_ADD('start_date',v) as day FROM ViewInt16 WHERE v<NumDays;
or
SELECT DATE_ADD('start_date',v) as day FROM ViewInt16 WHERE day<'end_date';
you might be able to speed this up with the slightly faster MAKEDATE function
SELECT MAKEDATE(start_year,1+v) as day FRON ViewInt16 WHERE day>'start_date' AND day<'end_date';
Please note that this tricks are VERY SLOW and only allow the creation of FINITE sequences in a pre-defined domain (for example int16 = 0...65536 )
I am sure you can modify the queries a bit to speed things up by hinting to MySQL where to stop calculating ;) (using ON clauses instead of WHERE clauses and stuff like that)
For example:
SELECT MIN + (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) FROM
ViewByteValues b0,
ViewByteValues b1,
ViewByteValues b2,
ViewByteValues b3
WHERE (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) < MAX-MIN;
will keep your SQL server busy for a few hours
However
SELECT MIN + (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) FROM
ViewByteValues b0
INNER JOIN ViewByteValues b1 ON (b1.v*256<(MAX-MIN))
INNER JOIN ViewByteValues b2 ON (b2.v*65536<(MAX-MIN))
INNER JOIN ViewByteValues b3 ON (b3.v*16777216<(MAX-MIN)
WHERE (b0.v + b1.v*256 + b2.v*65536 + b3.v*16777216) < (MAX-MIN);
will run reasonably fast - even if MAX-MIN is huge as long as you limit the result with LIMIT 1,30 or something. a COUNT(*) however will take ages and if you make the mistake of adding ORDER BY when MAX-MIN is bigger than say 100k it will again take several seconds to calculate...
There are severals hacks available for IE
Using conditional comments with stylesheet
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="only-ie.css" />
<![endif]-->
Using conditional comments with head section css
<!--[if IE]>
<style type="text/css">
/************ css for all IE browsers ****************/
</style>
<![endif]-->
Using conditional comments with HTML elements
<!--[if IE]> <div class="ie-only"> /*content*/ </div> <![endif]-->
Using media query
IE10+
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
selector { property:value; }
}
IE6,7,9,10
@media screen and (min-width: 640px), screen\9 {
selector { property:value; }
}
IE6,7
@media screen\9 {
selector { property:value; }
}
IE8
@media \0screen {
selector { property:value; }
}
IE6,7,8
@media \0screen\,screen\9 {
selector { property:value; }
}
IE9,10
@media screen and (min-width:0\0){
selector { property:value; }
}
I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:
div.hardware-accelarate {
-webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
I've made a plunkr setup for ya'll to test and tweak...
This is how I did it. In config.php
$config['HTML_TITLE'] = "SO TITLE test";
In applications/view/header.php (assuming html code)
<title><?=$this->config->item("HTML_TITLE");?> </title>
select *
from
tableA a
inner join
tableB b
on a.common = b.common
inner join
TableC c
on b.common = c.common
how about:
while(locations.Any())
{
list.Add(locations.Take(nSize).ToList());
locations= locations.Skip(nSize).ToList();
}
Nobody seems to have included the final step to make it easy to update attributes via binded variables. Here's what I came up with. Let me know if there is a better way of doing this.
XAML
<TextBox x:Name="txtLabel"
Text="{Binding Label}"
local:FocusExtension.IsFocused="{Binding txtLabel_IsFocused, Mode=TwoWay}"
/>
<Button x:Name="butEdit" Content="Edit"
Height="40"
IsEnabled="{Binding butEdit_IsEnabled}"
Command="{Binding cmdCapsuleEdit.Command}"
/>
ViewModel
public class LoginModel : ViewModelBase
{
public string txtLabel_IsFocused { get; set; }
public string butEdit_IsEnabled { get; set; }
public void SetProperty(string PropertyName, string value)
{
System.Reflection.PropertyInfo propertyInfo = this.GetType().GetProperty(PropertyName);
propertyInfo.SetValue(this, Convert.ChangeType(value, propertyInfo.PropertyType), null);
OnPropertyChanged(PropertyName);
}
private void Example_function(){
SetProperty("butEdit_IsEnabled", "False");
SetProperty("txtLabel_IsFocused", "True");
}
}
public void javascriptclick(String element)
{
WebElement webElement=driver.findElement(By.xpath(element));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();",webElement);
System.out.println("javascriptclick"+" "+ element);
}
The below code is working,
<style>
.PanelFloat {
position: fixed;
overflow: hidden;
z-index: 2400;
opacity: 0.70;
right: 30px;
top: 0px !important;
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-ms-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}
</style>
<script>
//The below script will keep the panel float on normal state
$(function () {
$(document).on('scroll', function () {
//Multiplication value shall be changed based on user window
$('#MyFloatPanel').css('top', 4 * ($(window).scrollTop() / 5));
});
});
//To make the panel float over a bootstrap model which has z-index: 2300, so i specified custom value as 2400
$(document).on('click', '.btnSearchView', function () {
$('#MyFloatPanel').addClass('PanelFloat');
});
$(document).on('click', '.btnSearchClose', function () {
$('#MyFloatPanel').removeClass('PanelFloat');
});
</script>
<div class="col-lg-12 col-md-12">
<div class="col-lg-8 col-md-8" >
//My scrollable content is here
</div>
//This below panel will float while scrolling the above div content
<div class="col-lg-4 col-md-4" id="MyFloatPanel">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">Panel Head </div>
<div class="panel-body ">//Your panel content</div>
</div>
</div>
</div>
</div>
See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.
Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.
The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.
It does look like the checkout --orphan
is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init
a repo, set up a remote
tracking branch (you do want the one branch only?), and then fetch
that single branch, which feels long winded with more opportunity for mistakes.
Edit: For the 'clone' step see this answer
Personally I would avoid iframes and go with an embed tag to create the view in the mouseover box.
<embed src="http://www.btf-internet.com" width="600" height="400" />
I too had the same problem. Digging into this I found that the Exception class has an args
attribute, which captures the arguments that were used to create the exception. If you narrow the exceptions that except will catch to a subset, you should be able to determine how they were constructed, and thus which argument contains the message.
try:
# do something that may raise an AuthException
except AuthException as ex:
if ex.args[0] == "Authentication Timeout.":
# handle timeout
else:
# generic handling
if you want to invoke ps1 scripts from cmd and pass arguments without invoking the script like
powershell.exe script.ps1 -c test
script -c test ( wont work )
you can do the following
setx PATHEXT "%PATHEXT%;.PS1;" /m
assoc .ps1=Microsoft.PowerShellScript.1
ftype Microsoft.PowerShellScript.1=powershell.exe "%1" %*
This is assuming powershell.exe is in your path
https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/ftype
Have you tried the json module? JSON format is very similar to python dictionary. And it's human readable/writable:
>>> import json
>>> d = {"one":1, "two":2}
>>> json.dump(d, open("text.txt",'w'))
This code dumps to a text file
$ cat text.txt
{"two": 2, "one": 1}
Also you can load from a JSON file:
>>> d2 = json.load(open("text.txt"))
>>> print d2
{u'two': 2, u'one': 1}
The above example using sort is close, but in the case of strings simply use SearchString:
files := []string{"Test.conf", "util.go", "Makefile", "misc.go", "main.go"}
target := "Makefile"
sort.Strings(files)
i := sort.SearchStrings(files, target)
if i < len(files) && files[i] == target {
fmt.Printf("found \"%s\" at files[%d]\n", files[i], i)
}
If I get your question correctly, you could do something like this.
>>> import matplotlib.pyplot as plt
>>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
>>> from math import log
>>> testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList]
>>> testList2
[(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)]
>>> zip(*testList2)
[(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)]
>>> plt.scatter(*zip(*testList2))
>>> plt.show()
which would give you something like
Or as a line plot,
>>> plt.plot(*zip(*testList2))
>>> plt.show()
EDIT - If you want to add a title and labels for the axis, you could do something like
>>> plt.scatter(*zip(*testList2))
>>> plt.title('Random Figure')
>>> plt.xlabel('X-Axis')
>>> plt.ylabel('Y-Axis')
>>> plt.show()
which would give you
You can maintain your html as it is but use this php code
<?php
$name = $_POST['name'];
$purchase1 = $_POST['Tea'];
$purchase2 =$_POST['Coffee'];
?>
I believe that what you are looking for is error option for the jquery ajax object
getJSON is a wrapper to the $.ajax
object, but it doesn't provide you with access to the error option.
EDIT: dcneiner has given a good example of the code you would need to use. (Even before I could post my reply)
With the following you can insert multiple values and also have default values but you're creating a new dictionary.
d = {**{ key: value }, **default_values}
I've tested it with the most voted answer and on average this is faster as it can be seen in the following example, .
Speed test comparing a for loop based method with a dict comprehension with unpack operator method.
if no copy (d = default_vals.copy()
) is made on the first case then the most voted answer would be faster once we reach orders of magnitude of 10**5
and greater. Memory footprint of both methods are the same.
Difference between a Spy and a Mock
When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it.
In the following example – we create a mock of the ArrayList class:
@Test
public void whenCreateMock_thenCreated() {
List mockedList = Mockito.mock(ArrayList.class);
mockedList.add("one");
Mockito.verify(mockedList).add("one");
assertEquals(0, mockedList.size());
}
As you can see – adding an element into the mocked list doesn’t actually add anything – it just calls the method with no other side-effect. A spy on the other hand will behave differently – it will actually call the real implementation of the add method and add the element to the underlying list:
@Test
public void whenCreateSpy_thenCreate() {
List spyList = Mockito.spy(new ArrayList());
spyList.add("one");
Mockito.verify(spyList).add("one");
assertEquals(1, spyList.size());
}
Here we can surely say that the real internal method of the object was called because when you call the size() method you get the size as 1, but this size() method isn’t been mocked! So where does 1 come from? The internal real size() method is called as size() isn’t mocked (or stubbed) and hence we can say that the entry was added to the real object.
Source: http://www.baeldung.com/mockito-spy + self notes.
You can do something like this in you getJsonResponse
function -
jData, err := json.Marshal(Data)
if err != nil {
// handle error
}
w.Header().Set("Content-Type", "application/json")
w.Write(jData)
Step 1: Create a class AppStatus in your project(you can give any other name also). Then please paste the given below lines into your code:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class AppStatus {
private static AppStatus instance = new AppStatus();
static Context context;
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo;
boolean connected = false;
public static AppStatus getInstance(Context ctx) {
context = ctx.getApplicationContext();
return instance;
}
public boolean isOnline() {
try {
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
connected = networkInfo != null && networkInfo.isAvailable() &&
networkInfo.isConnected();
return connected;
} catch (Exception e) {
System.out.println("CheckConnectivity Exception: " + e.getMessage());
Log.v("connectivity", e.toString());
}
return connected;
}
}
Step 2: Now to check if the your device has network connectivity then just add this code snippet where ever you want to check ...
if (AppStatus.getInstance(this).isOnline()) {
Toast.makeText(this,"You are online!!!!",8000).show();
} else {
Toast.makeText(this,"You are not online!!!!",8000).show();
Log.v("Home", "############################You are not online!!!!");
}
If your using PHP and MySQL you can use the mysql_insert_id() function which will tell you the ID of item you Just instered.
But without your Language and DBMS I'm just shooting in the dark here.
Installing vc_redist.x86.exe works for me even though you have a 64-bit machine.
You may want to wrap that functionality up into a filter, this way you don't have to put the mySplit function in all of your controllers. For example
angular.module('myModule', [])
.filter('split', function() {
return function(input, splitChar, splitIndex) {
// do some bounds checking here to ensure it has that index
return input.split(splitChar)[splitIndex];
}
});
From here, you can use a filter as you originally intended
{{test | split:',':0}}
{{test | split:',':0}}
More info at http://docs.angularjs.org/guide/filter (thanks ross)
Plunkr @ http://plnkr.co/edit/NA4UeL
I have also encountered this error for a Web API (.Net Core 3.0) action that was binding to a string
instead to an object
or a JObject
. The JSON was correct, but the binder tried to get a string from the JSON structure and failed.
So, instead of:
[HttpPost("[action]")]
public object Search([FromBody] string data)
I had to use the more specific:
[HttpPost("[action]")]
public object Search([FromBody] JObject data)
This error means you didn't add some of dependencies.
Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64
macro and other printf
issues altogether:
#include <fmt/core.h>
int main() {
uint64_t ui64 = 90;
fmt::print("test uint64_t : {}\n", ui64);
}
The formatting facility based on this library is proposed for standardization in C++20: P0645.
Disclaimer: I'm the author of {fmt}.
To allow receiving & sending cookies by a CORS request successfully, do the following.
Back-end (server):
Set the HTTP header Access-Control-Allow-Credentials
value to true
.
Also, make sure the HTTP headers Access-Control-Allow-Origin
and Access-Control-Allow-Headers
are set and not with a wildcard *
.
Recommended Cookie settings per Chrome and Firefox update in 2021: SameSite=None
and Secure
. See MDN documentation
For more info on setting CORS in express js read the docs here
Front-end (client): Set the XMLHttpRequest.withCredentials
flag to true
, this can be achieved in different ways depending on the request-response library used:
jQuery 1.5.1 xhrFields: {withCredentials: true}
ES6 fetch() credentials: 'include'
axios: withCredentials: true
Avoid having to use CORS in combination with cookies. You can achieve this with a proxy.
If you for whatever reason don't avoid it. The solution is above.
It turned out that Chrome won't set the cookie if the domain contains a port. Setting it for localhost
(without port) is not a problem. Many thanks to Erwin for this tip!
If I understood what you wanted to do, this is what I do inside a function constructor.
if (!(this instanceof arguments.callee)) {
throw "ReferenceError: " + arguments.callee.name + " is not defined";
}
You can do it with PhantomJSDriver.
PhantomJSDriver pd = ((PhantomJSDriver) ((WebDriverFacade) getDriver()).getProxiedDriver());
pd.executePhantomJS(
"this.onResourceRequested = function(request, net) {" +
" net.setHeader('header-name', 'header-value')" +
"};");
Using the request object, you can filter also so the header won't be set for every request.
I had to remove .idea and target folders and after reading all comments this worked for me:
git rm -r .idea
git rm -r target
git commit -m 'removed .idea folder'
and then push to master
This is relatively simple if you use pylab (included with matplotlib) instead of matplotlib directly. Start off with a list of filenames and legend names, like [ ('name of file 1', 'label 1'), ('name of file 2', 'label 2'), ...]. Then you can use something like the following:
import pylab
datalist = [ ( pylab.loadtxt(filename), label ) for filename, label in list_of_files ]
for data, label in datalist:
pylab.plot( data[:,0], data[:,1], label=label )
pylab.legend()
pylab.title("Title of Plot")
pylab.xlabel("X Axis Label")
pylab.ylabel("Y Axis Label")
You also might want to add something like fmt='o' to the plot command, in order to change from a line to points. By default, matplotlib with pylab plots onto the same figure without clearing it, so you can just run the plot command multiple times.
You can extend the abstract class with an anonymous class in your test. For example (using Junit 4):
private AbstractClassName classToTest;
@Before
public void preTestSetup()
{
classToTest = new AbstractClassName() { };
}
// Test the AbstractClassName methods.
Here's how you can change the android sdk path in Android studio:
Note: If changes do not take effect, restarting android studio should fix the problem.
You could use table
, i.e.
n_occur <- data.frame(table(vocabulary$id))
gives you a data frame with a list of id
s and the number of times they occurred.
n_occur[n_occur$Freq > 1,]
tells you which id
s occurred more than once.
vocabulary[vocabulary$id %in% n_occur$Var1[n_occur$Freq > 1],]
returns the records with more than one occurrence.
List<WebElement> myElements = driver.findElements(By.xpath("some/path//a"));
System.out.println("Size of List: "+myElements.size());
for(WebElement e : myElements)
{
System.out.print("Text within the Anchor tab"+e.getText()+"\t");
System.out.println("Anchor: "+e.getAttribute("href"));
}
//NOTE: "//a" will give you all the anchors there on after the point your XPATH has reached.
I've create a ClassPathResourceReader class in a java 8 way to make easy read files from classpath
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import org.springframework.core.io.ClassPathResource;
public final class ClassPathResourceReader {
private final String path;
private String content;
public ClassPathResourceReader(String path) {
this.path = path;
}
public String getContent() {
if (content == null) {
try {
ClassPathResource resource = new ClassPathResource(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
content = reader.lines().collect(Collectors.joining("\n"));
reader.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
return content;
}
}
Utilization:
String content = new ClassPathResourceReader("data.sql").getContent();
You need to escape the double quotes like this:
echo "<script type=\"text/javascript\">";
echo "document.write(\"Hello World!\")";
echo "</script>";
or use single quotes inside the double quotes instead, like this:
echo "<script type='text/javascript'>";
echo "document.write('Hello World!')";
echo "</script>";
or the other way around, like this:
echo '<script type="text/javascript">';
echo 'document.write("Hello World!")';
echo '</script>';
Also, checkout the PHP Manual for more info on Strings.
Also, why would you want to print JavaScript using PHP? I feel like there's something wrong with your design.
Well, I used to do this way:
Imagine, you have 500 commits, and your erroneous commit message is in r.498.
hg qimport -r 498:tip
hg qpop -a
joe .hg/patches/498.diff
(change the comment, after the mercurial header)
hg qpush -a
hg qdelete -r qbase:qtip
TypeScript isn't giving you a gun to shoot yourself in the foot with.
The iterator variable is a string because it is a string, full stop. Observe:
var obj = {};
obj['0'] = 'quote zero quote';
obj[0.0] = 'zero point zero';
obj['[object Object]'] = 'literal string "[object Object]"';
obj[<any>obj] = 'this obj'
obj[<any>undefined] = 'undefined';
obj[<any>"undefined"] = 'the literal string "undefined"';
for(var key in obj) {
console.log('Type: ' + typeof key);
console.log(key + ' => ' + obj[key]);
}
How many key/value pairs are in obj
now? 6, more or less? No, 3, and all of the keys are strings:
Type: string
0 => zero point zero
Type: string
[object Object] => this obj;
Type: string
undefined => the literal string "undefined"
You could wrap your maven command in a bash script:
#!/bin/bash
export YOUR_VAR=thevalue
mvn test
unset YOUR_VAR
Use the index
attribute of DataFrame
. Note that I don't type all the rows in the example.
In [14]: df = data.groupby(['Country','Place'])['Value'].max()
In [15]: df.index
Out[15]:
MultiIndex
[Spain Manchester, UK London , US Mchigan , NewYork ]
In [16]: df.index[0]
Out[16]: ('Spain', 'Manchester')
In [17]: df.index[1]
Out[17]: ('UK', 'London')
You can also get the value by that index:
In [21]: for index in df.index:
print index, df[index]
....:
('Spain', 'Manchester') 512
('UK', 'London') 778
('US', 'Mchigan') 854
('US', 'NewYork') 562
Sorry for misunderstanding what you want, try followings:
In [52]: s=data.max()
In [53]: print '%s, %s, %s' % (s['Country'], s['Place'], s['Value'])
US, NewYork, 854
Begginer here, so please let me know if I am way of, but I'd do it like this:
def prime(n):
count = 0
for i in range(1, (n+1)):
if n % i == 0:
count += 1
if count > 2:
print "Not a prime"
else:
print "A prime"
Yes, there are negative effects from this:
If you script out a change blocked by this flag you get something like the script below (all i am turning the ID column in Contact into an autonumbered IDENTITY column, but the table has dependencies). Note potential errors that can occur while the following is running:
--
/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
DROP CONSTRAINT fk_Contact_AddressType
GO
ALTER TABLE ref.ContactpointType SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
DROP CONSTRAINT fk_contact_profile
GO
ALTER TABLE raw.Profile SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE raw.Tmp_Contact
(
ContactID int NOT NULL IDENTITY (1, 1),
ProfileID int NOT NULL,
AddressType char(2) NOT NULL,
ContactText varchar(250) NULL
) ON [PRIMARY]
GO
ALTER TABLE raw.Tmp_Contact SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT raw.Tmp_Contact ON
GO
IF EXISTS(SELECT * FROM raw.Contact)
EXEC('INSERT INTO raw.Tmp_Contact (ContactID, ProfileID, AddressType, ContactText)
SELECT ContactID, ProfileID, AddressType, ContactText FROM raw.Contact WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT raw.Tmp_Contact OFF
GO
ALTER TABLE raw.PostalAddress
DROP CONSTRAINT fk_AddressProfile
GO
ALTER TABLE raw.MarketingFlag
DROP CONSTRAINT fk_marketingflag_contact
GO
ALTER TABLE raw.Phones
DROP CONSTRAINT fk_phones_contact
GO
DROP TABLE raw.Contact
GO
EXECUTE sp_rename N'raw.Tmp_Contact', N'Contact', 'OBJECT'
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
Idx_Contact_1 PRIMARY KEY CLUSTERED
(
ProfileID,
ContactID
)
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
Idx_Contact UNIQUE NONCLUSTERED
(
ProfileID,
ContactID
)
GO
CREATE NONCLUSTERED INDEX idx_Contact_0 ON raw.Contact
(
AddressType
)
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
fk_contact_profile FOREIGN KEY
(
ProfileID
) REFERENCES raw.Profile
(
ProfileID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
fk_Contact_AddressType FOREIGN KEY
(
AddressType
) REFERENCES ref.ContactpointType
(
ContactPointTypeCode
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Phones ADD CONSTRAINT
fk_phones_contact FOREIGN KEY
(
ProfileID,
PhoneID
) REFERENCES raw.Contact
(
ProfileID,
ContactID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.Phones SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.MarketingFlag ADD CONSTRAINT
fk_marketingflag_contact FOREIGN KEY
(
ProfileID,
ContactID
) REFERENCES raw.Contact
(
ProfileID,
ContactID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.MarketingFlag SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.PostalAddress ADD CONSTRAINT
fk_AddressProfile FOREIGN KEY
(
ProfileID,
AddressID
) REFERENCES raw.Contact
(
ProfileID,
ContactID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.PostalAddress SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
If you want to go even further than @tetra with ES6 you can use the Object spread syntax and do something like this:
let john = {
firstName: "John",
lastName: "Doe",
};
let people = new Array(10).fill().map((e, i) => {(...john, id: i});
Set
'auth' => false,
Also, see if port 25 works.
When your file is created. Instead of creating a file with content is empty. Replace with:
json.dump({}, file)
As per user667073 suggested, except reordering the backslash replacement first, and fixing the quote replacement
escape = function (str) {
return str
.replace(/[\\]/g, '\\\\')
.replace(/[\"]/g, '\\\"')
.replace(/[\/]/g, '\\/')
.replace(/[\b]/g, '\\b')
.replace(/[\f]/g, '\\f')
.replace(/[\n]/g, '\\n')
.replace(/[\r]/g, '\\r')
.replace(/[\t]/g, '\\t');
};
It's been a while since I C++'d but these answers are off a bit.
As far as the size goes, 'int' isn't anything. It's a notional value of a standard integer; assumed to be fast for purposes of things like iteration. It doesn't have a preset size.
So, the answers are correct with respect to the differences between int and uint, but are incorrect when they talk about "how large they are" or what their range is. That size is undefined, or more accurately, it will change with the compiler and platform.
It's never polite to discuss the size of your bits in public.
When you compile a program, int does have a size, as you've taken the abstract C/C++ and turned it into concrete machine code.
So, TODAY, practically speaking with most common compilers, they are correct. But do not assume this.
Specifically: if you're writing a 32 bit program, int will be one thing, 64 bit, it can be different, and 16 bit is different. I've gone through all three and briefly looked at 6502 shudder
A brief google search shows this: https://www.tutorialspoint.com/cprogramming/c_data_types.htm This is also good info: https://docs.oracle.com/cd/E19620-01/805-3024/lp64-1/index.html
use int if you really don't care how large your bits are; it can change.
Use size_t and ssize_t if you want to know how large something is.
If you're reading or writing binary data, don't use int. Use a (usually platform/source dependent) specific keyword. WinSDK has plenty of good, maintainable examples of this. Other platforms do too.
I've spent a LOT of time going through code from people that "SMH" at the idea that this is all just academic/pedantic. These ate the people that write unmaintainable code. Sure, it's easy to use type 'int' and use it without all the extra darn typing. It's a lot of work to figure out what they really meant, and a bit mind-numbing.
It's crappy coding when you mix int.
use int and uint when you just want a fast integer and don't care about the range (other than signed/unsigned).
Make sure you've placed the connection string in the startup project's ROOT web.config.
I know I'm kinda stating the obvious here, but it happened to me too - though I already HAD the connection string in my MVC project's Web.Config (the .edmx file was placed at a different, class library project) and I couldn't figure out why I keep getting an exception... Long story short, I copied the connection string to the Views\Web.Config by mistake, in a strange combination of tiredness and not-scrolling-to-the-bottom-of-the-solution-explorer scenario. Yeah, these things happen to veteran developers as well :)
Update:
This answer was for a much older release of Ui-Router. For the more recent releases (0.2.5+), please use the helper directive ui-sref-active
. Details here.
Original Answer:
Include the $state service in your controller. You can assign this service to a property on your scope.
An example:
$scope.$state = $state;
Then to get the current state in your templates:
$state.current.name
To check if a state is current active:
$state.includes('stateName');
This method returns true if the state is included, even if it's part of a nested state. If you were at a nested state, user.details
, and you checked for $state.includes('user')
, it'd return true.
In your class example, you'd do something like this:
ng-class="{active: $state.includes('stateName')}"
The simplest way is to use slice. If x is your string variable then x[:-1] will return the string variable without the last character. (BTW, x[-1] is the last character in the string variable) You are looking for
my_file_path = '/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/' my_file_path = my_file_path[:-1]
__all__
is very good - it helps guide import statements without automatically importing modules
http://docs.python.org/tutorial/modules.html#importing-from-a-package
using __all__
and import *
is redundant, only __all__
is needed
I think one of the most powerful reasons to use import *
in an __init__.py
to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py
files empty.
for example:
foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo
then the app grows and now it's a whole folder
foo/
__init__.py
foofactories.py
tallFoos.py
shortfoos.py
mediumfoos.py
santaslittlehelperfoo.py
superawsomefoo.py
anotherfoo.py
then the init script can say
__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo
so that a script written to do the following does not break during the change:
from foo import fooFactory, tallFoo, shortFoo
If you want to use MSBuild for .Net 4 then you can use the following PowerShell command to get the executable's path. If you want version 2.0 or 3.5 then just change the $dotNetVersion variable.
To run the executable you'll need to prepend the $msbuild variable with &. That will execute the variable.
# valid versions are [2.0, 3.5, 4.0]
$dotNetVersion = "4.0"
$regKey = "HKLM:\software\Microsoft\MSBuild\ToolsVersions\$dotNetVersion"
$regProperty = "MSBuildToolsPath"
$msbuildExe = join-path -path (Get-ItemProperty $regKey).$regProperty -childpath "msbuild.exe"
&$msbuildExe
There are two problems with your xpath - first you need to remove the child selector from after Data
like phihag mentioned. Also you forgot to include root
in your xpath. Here is what you want to do:
select="/root/DataSet/Data[@Value1='2']/@Value2"
Here's the one that may be little easier to read. Hope this is helpful.
from PIL import Image
from PIL import ExifTags
exifData = {}
img = Image.open(picture.jpg)
exifDataRaw = img._getexif()
for tag, value in exifDataRaw.items():
decodedTag = ExifTags.TAGS.get(tag, tag)
exifData[decodedTag] = value
alternatively, SQL%ROWCOUNT
you can use this within the procedure without any need to declare a variable
You can use Object.prototype.toString
to easily check if an object is an Error
, which will work for different frames as well.
function isError(obj){
return Object.prototype.toString.call(obj) === "[object Error]";
}
function isError(obj){
return Object.prototype.toString.call(obj) === "[object Error]";
}
console.log("Error:", isError(new Error));
console.log("RangeError:", isError(new RangeError));
console.log("SyntaxError:", isError(new SyntaxError));
console.log("Object:", isError({}));
console.log("Array:", isError([]));
_x000D_
This behavior is guaranteed by the ECMAScript Language Specification.
When the toString method is called, the following steps are taken:
- If the this value is undefined, return "[object Undefined]".
- If the this value is null, return "[object Null]".
- Let O be the result of calling ToObject passing the this value as the argument.
- Let class be the value of the [[Class]] internal property of O.
- Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
Properties of Error Instances:
Error instances inherit properties from the Error prototype object and their
[[Class]]
internal property value is "Error". Error instances have no special properties.
CSS 3 introduces rgba colour, and you can combine it with graphics for a backwards compatible solution.
Nope, ThreadAbortException
is thrown by a simple Response.Redirect
The form
tag needs some attributes set:
action
: The URL that the form data is sent to on submit. Generate it with url_for
. It can be omitted if the same URL handles showing the form and processing the data.method="post"
: Submits the data as form data with the POST method. If not given, or explicitly set to get
, the data is submitted in the query string (request.args
) with the GET method instead.enctype="multipart/form-data"
: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.The input
tag needs a name
parameter.
Add a view to handle the submitted data, which is in request.form
under the same key as the input's name
. Any file inputs will be in request.files
.
@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action
to that view's URL using url_for
:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
My solution that works for me for multiline ellipsis:
.crd-para {
color: $txt-clr-main;
line-height: 2rem;
font-weight: 600;
margin-bottom: 1rem !important;
overflow: hidden;
span::after {
content: "...";
padding-left: 0.125rem;
}
}
Go to the Declaration of the desired object and mark it Shared.
Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX
Seems the command should be without the square blanket
EXEC sp_msforeachtable 'drop table ?'
there's an interesting way to achive another goal which is to have a strongly type class base on json with a very powerfull tools that i used few days ago for first time to translate tradedoubler json result into classes
Is a simple tool: copy your json source paste and in few second you will have a strongly typed class json oriented . In this manner you will use these classes which is more powerful and simply to use.
this will work
<h:outputText value=" " />
Suresh, you don't need use anything in your codes. What you need is just something like this:
.others {_x000D_
color:black_x000D_
}
_x000D_
<select id="select">_x000D_
<option style="color:gray" value="null">select one option</option>_x000D_
<option value="1" class="others">one</option>_x000D_
<option value="2" class="others">two</option>_x000D_
</select>
_x000D_
But as you can see, because your first item in options is the first thing that your select control shows, you can not see its assigned color. While if you open the select list and see the opened items, you will see you could assign a gray color to the first option. So you need something else in jQuery.
$(document).ready(function() {
$('#select').css('color','gray');
$('#select').change(function() {
var current = $('#select').val();
if (current != 'null') {
$('#select').css('color','black');
} else {
$('#select').css('color','gray');
}
});
});
This is my code in jsFiddle.
Here is a query used by Oracle SQL Developer in its Tablespaces view
select a.tablespace_name as "Tablespace Name",
round(a.bytes_alloc / 1024 / 1024) "Allocated (MB)",
round(nvl(b.bytes_free, 0) / 1024 / 1024) "Free (MB)",
round((a.bytes_alloc - nvl(b.bytes_free, 0)) / 1024 / 1024) "Used (MB)",
round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Free",
100 - round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Used",
round(maxbytes/1024 / 1024) "Max. Bytes (MB)"
from ( select f.tablespace_name,
sum(f.bytes) bytes_alloc,
sum(decode(f.autoextensible, 'YES',f.maxbytes,'NO', f.bytes)) maxbytes
from dba_data_files f
group by tablespace_name) a,
( select f.tablespace_name,
sum(f.bytes) bytes_free
from dba_free_space f
group by tablespace_name) b
where a.tablespace_name = b.tablespace_name (+)
union all
select
h.tablespace_name as tablespace_name,
round(sum(h.bytes_free + h.bytes_used) / 1048576) megs_alloc,
round(sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / 1048576) megs_free,
round(sum(nvl(p.bytes_used, 0))/ 1048576) megs_used,
round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) Pct_Free,
100 - round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) pct_used,
round(sum(f.maxbytes) / 1048576) max
from sys.v_$TEMP_SPACE_HEADER h, sys.v_$Temp_extent_pool p, dba_temp_files f
where p.file_id(+) = h.file_id
and p.tablespace_name(+) = h.tablespace_name
and f.file_id = h.file_id
and f.tablespace_name = h.tablespace_name
group by h.tablespace_name
ORDER BY 2;
The Throwable class provides two methods named printStackTrace
, one that accepts a PrintWriter
and one that takes in a PrintStream
, that outputs the stack trace to the given stream. Consider using one of these.
Multi-scale plots are rare to find beyond two axes... Luckily in Matlab it is possible, but you have to fully overlap axes and play with tickmarks so as not to hide info.
Below is a nice working sample. I hope this is what you are looking for (although colors could be much nicer)!
close all
clear all
display('Generating data');
x = 0:10;
y1 = rand(1,11);
y2 = 10.*rand(1,11);
y3 = 100.*rand(1,11);
y4 = 100.*rand(1,11);
display('Plotting');
figure;
ax1 = gca;
get(ax1,'Position')
set(ax1,'XColor','k',...
'YColor','b',...
'YLim',[0,1],...
'YTick',[0, 0.2, 0.4, 0.6, 0.8, 1.0]);
line(x, y1, 'Color', 'b', 'LineStyle', '-', 'Marker', '.', 'Parent', ax1)
ax2 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','left',...
'Color','none',...
'XColor','k',...
'YColor','r',...
'YLim',[0,10],...
'YTick',[1, 3, 5, 7, 9],...
'XTick',[],'XTickLabel',[]);
line(x, y2, 'Color', 'r', 'LineStyle', '-', 'Marker', '.', 'Parent', ax2)
ax3 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','right',...
'Color','none',...
'XColor','k',...
'YColor','g',...
'YLim',[0,100],...
'YTick',[0, 20, 40, 60, 80, 100],...
'XTick',[],'XTickLabel',[]);
line(x, y3, 'Color', 'g', 'LineStyle', '-', 'Marker', '.', 'Parent', ax3)
ax4 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','right',...
'Color','none',...
'XColor','k',...
'YColor','c',...
'YLim',[0,100],...
'YTick',[10, 30, 50, 70, 90],...
'XTick',[],'XTickLabel',[]);
line(x, y4, 'Color', 'c', 'LineStyle', '-', 'Marker', '.', 'Parent', ax4)
(source: pablorodriguez.info)
Since you are the only user:
git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}
( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )
Without doing any changes to your local repo, you can also do something like:
git push -f origin <sha_of_previous_commit>:master
Generally, in published repos, it is safer to do git revert
and then git push
How can I make as "perfect" a subclass of dict as possible?
The end goal is to have a simple dict in which the keys are lowercase.
If I override
__getitem__
/__setitem__
, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?Am I preventing pickling from working, and do I need to implement
__setstate__
etc?Do I need repr, update and
__init__
?Should I just use
mutablemapping
(it seems one shouldn't useUserDict
orDictMixin
)? If so, how? The docs aren't exactly enlightening.
The accepted answer would be my first approach, but since it has some issues,
and since no one has addressed the alternative, actually subclassing a dict
, I'm going to do that here.
This seems like a rather simple request to me:
How can I make as "perfect" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase.
The accepted answer doesn't actually subclass dict
, and a test for this fails:
>>> isinstance(MyTransformedDict([('Test', 'test')]), dict)
False
Ideally, any type-checking code would be testing for the interface we expect, or an abstract base class, but if our data objects are being passed into functions that are testing for dict
- and we can't "fix" those functions, this code will fail.
Other quibbles one might make:
fromkeys
. The accepted answer also has a redundant __dict__
- therefore taking up more space in memory:
>>> s.foo = 'bar'
>>> s.__dict__
{'foo': 'bar', 'store': {'test': 'test'}}
dict
We can reuse the dict methods through inheritance. All we need to do is create an interface layer that ensures keys are passed into the dict in lowercase form if they are strings.
If I override
__getitem__
/__setitem__
, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?
Well, implementing them each individually is the downside to this approach and the upside to using MutableMapping
(see the accepted answer), but it's really not that much more work.
First, let's factor out the difference between Python 2 and 3, create a singleton (_RaiseKeyError
) to make sure we know if we actually get an argument to dict.pop
, and create a function to ensure our string keys are lowercase:
from itertools import chain
try: # Python 2
str_base = basestring
items = 'iteritems'
except NameError: # Python 3
str_base = str, bytes, bytearray
items = 'items'
_RaiseKeyError = object() # singleton for no-default behavior
def ensure_lower(maybe_str):
"""dict keys can be any hashable object - only call lower if str"""
return maybe_str.lower() if isinstance(maybe_str, str_base) else maybe_str
Now we implement - I'm using super
with the full arguments so that this code works for Python 2 and 3:
class LowerDict(dict): # dicts take a mapping or iterable as their optional first argument
__slots__ = () # no __dict__ - that would be redundant
@staticmethod # because this doesn't make sense as a global function.
def _process_args(mapping=(), **kwargs):
if hasattr(mapping, items):
mapping = getattr(mapping, items)()
return ((ensure_lower(k), v) for k, v in chain(mapping, getattr(kwargs, items)()))
def __init__(self, mapping=(), **kwargs):
super(LowerDict, self).__init__(self._process_args(mapping, **kwargs))
def __getitem__(self, k):
return super(LowerDict, self).__getitem__(ensure_lower(k))
def __setitem__(self, k, v):
return super(LowerDict, self).__setitem__(ensure_lower(k), v)
def __delitem__(self, k):
return super(LowerDict, self).__delitem__(ensure_lower(k))
def get(self, k, default=None):
return super(LowerDict, self).get(ensure_lower(k), default)
def setdefault(self, k, default=None):
return super(LowerDict, self).setdefault(ensure_lower(k), default)
def pop(self, k, v=_RaiseKeyError):
if v is _RaiseKeyError:
return super(LowerDict, self).pop(ensure_lower(k))
return super(LowerDict, self).pop(ensure_lower(k), v)
def update(self, mapping=(), **kwargs):
super(LowerDict, self).update(self._process_args(mapping, **kwargs))
def __contains__(self, k):
return super(LowerDict, self).__contains__(ensure_lower(k))
def copy(self): # don't delegate w/ super - dict.copy() -> dict :(
return type(self)(self)
@classmethod
def fromkeys(cls, keys, v=None):
return super(LowerDict, cls).fromkeys((ensure_lower(k) for k in keys), v)
def __repr__(self):
return '{0}({1})'.format(type(self).__name__, super(LowerDict, self).__repr__())
We use an almost boiler-plate approach for any method or special method that references a key, but otherwise, by inheritance, we get methods: len
, clear
, items
, keys
, popitem
, and values
for free. While this required some careful thought to get right, it is trivial to see that this works.
(Note that haskey
was deprecated in Python 2, removed in Python 3.)
Here's some usage:
>>> ld = LowerDict(dict(foo='bar'))
>>> ld['FOO']
'bar'
>>> ld['foo']
'bar'
>>> ld.pop('FoO')
'bar'
>>> ld.setdefault('Foo')
>>> ld
{'foo': None}
>>> ld.get('Bar')
>>> ld.setdefault('Bar')
>>> ld
{'bar': None, 'foo': None}
>>> ld.popitem()
('bar', None)
Am I preventing pickling from working, and do I need to implement
__setstate__
etc?
And the dict subclass pickles just fine:
>>> import pickle
>>> pickle.dumps(ld)
b'\x80\x03c__main__\nLowerDict\nq\x00)\x81q\x01X\x03\x00\x00\x00fooq\x02Ns.'
>>> pickle.loads(pickle.dumps(ld))
{'foo': None}
>>> type(pickle.loads(pickle.dumps(ld)))
<class '__main__.LowerDict'>
__repr__
Do I need repr, update and
__init__
?
We defined update
and __init__
, but you have a beautiful __repr__
by default:
>>> ld # without __repr__ defined for the class, we get this
{'foo': None}
However, it's good to write a __repr__
to improve the debugability of your code. The ideal test is eval(repr(obj)) == obj
. If it's easy to do for your code, I strongly recommend it:
>>> ld = LowerDict({})
>>> eval(repr(ld)) == ld
True
>>> ld = LowerDict(dict(a=1, b=2, c=3))
>>> eval(repr(ld)) == ld
True
You see, it's exactly what we need to recreate an equivalent object - this is something that might show up in our logs or in backtraces:
>>> ld
LowerDict({'a': 1, 'c': 3, 'b': 2})
Should I just use
mutablemapping
(it seems one shouldn't useUserDict
orDictMixin
)? If so, how? The docs aren't exactly enlightening.
Yeah, these are a few more lines of code, but they're intended to be comprehensive. My first inclination would be to use the accepted answer, and if there were issues with it, I'd then look at my answer - as it's a little more complicated, and there's no ABC to help me get my interface right.
Premature optimization is going for greater complexity in search of performance.
MutableMapping
is simpler - so it gets an immediate edge, all else being equal. Nevertheless, to lay out all the differences, let's compare and contrast.
I should add that there was a push to put a similar dictionary into the collections
module, but it was rejected. You should probably just do this instead:
my_dict[transform(key)]
It should be far more easily debugable.
There are 6 interface functions implemented with the MutableMapping
(which is missing fromkeys
) and 11 with the dict
subclass. I don't need to implement __iter__
or __len__
, but instead I have to implement get
, setdefault
, pop
, update
, copy
, __contains__
, and fromkeys
- but these are fairly trivial, since I can use inheritance for most of those implementations.
The MutableMapping
implements some things in Python that dict
implements in C - so I would expect a dict
subclass to be more performant in some cases.
We get a free __eq__
in both approaches - both of which assume equality only if another dict is all lowercase - but again, I think the dict
subclass will compare more quickly.
MutableMapping
is simpler with fewer opportunities for bugs, but slower, takes more memory (see redundant dict), and fails isinstance(x, dict)
dict
is faster, uses less memory, and passes isinstance(x, dict)
, but it has greater complexity to implement.Which is more perfect? That depends on your definition of perfect.
The way I could mitigate the JSON Array to collection of LinkedHashMap objects problem was by using CollectionType
rather than a TypeReference
.
This is what I did and worked:
public <T> List<T> jsonArrayToObjectList(String json, Class<T> tClass) throws IOException {
ObjectMapper mapper = new ObjectMapper();
CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, tClass);
List<T> ts = mapper.readValue(json, listType);
LOGGER.debug("class name: {}", ts.get(0).getClass().getName());
return ts;
}
Using the TypeReference
, I was still getting an ArrayList of LinkedHashMaps, i.e. does not work:
public <T> List<T> jsonArrayToObjectList(String json, Class<T> tClass) throws IOException {
ObjectMapper mapper = new ObjectMapper();
List<T> ts = mapper.readValue(json, new TypeReference<List<T>>(){});
LOGGER.debug("class name: {}", ts.get(0).getClass().getName());
return ts;
}
Use this code to generate horizontal scrolling blocks contents. I got this from here http://www.htmlexplorer.com/2014/02/horizontal-scrolling-webpage-content.html
<html>
<title>HTMLExplorer Demo: Horizontal Scrolling Content</title>
<head>
<style type="text/css">
#outer_wrapper {
overflow: scroll;
width:100%;
}
#outer_wrapper #inner_wrapper {
width:6000px; /* If you have more elements, increase the width accordingly */
}
#outer_wrapper #inner_wrapper div.box { /* Define the properties of inner block */
width: 250px;
height:300px;
float: left;
margin: 0 4px 0 0;
border:1px grey solid;
}
</style>
</head>
<body>
<div id="outer_wrapper">
<div id="inner_wrapper">
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<!-- more boxes here -->
</div>
</div>
</body>
</html>
Comma separate the values:
UPDATE settings SET postsPerPage = $postsPerPage, style = $style WHERE id = '1'"
Sheet.getPhysicalNumberOfRows()
does not involve some empty rows.
If you want to loop for all rows, do not use this to know the loop size.
Another possibility with Guava:
dependency: compile 'com.google.guava:guava:11.0.2'
import com.google.common.io.ByteStreams;
...
String total = new String(ByteStreams.toByteArray(inputStream ));
after installing the 1.7jdk from oracle, i changed my bash scripts to add:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_13.jdk/Contents/Home
and then running java -version
showed the right version.
Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.
set nocount on
create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
declare @PersonID int
set @PersonID = 1
IF EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Posted_Flag = 1
AND Staff_Id = @PersonID
)
BEGIN
RAISERROR('Timesheets have already been posted!', 16, 1)
ROLLBACK TRAN
END
ELSE
IF NOT EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Staff_Id = @PersonID
)
BEGIN
RAISERROR('Default list has not been loaded!', 16, 1)
ROLLBACK TRAN
END
ELSE
print 'No problems here'
drop table Timesheet_Hours
You can. Transparent canvas can be quickly faded by using destination-out global composite operation. It's not 100% perfect, sometimes it leaves some traces but it could be tweaked, depending what's needed (i.e. use 'source-over' and fill it with white color with alpha at 0.13, then fade to prepare the canvas).
// Fill canvas using 'destination-out' and alpha at 0.05
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = "rgba(255, 255, 255, 0.05)";
ctx.beginPath();
ctx.fillRect(0, 0, width, height);
ctx.fill();
// Set the default mode.
ctx.globalCompositeOperation = 'source-over';
Spring Boot 1.4 Use this for Javascript HTML Json all compressions.
server.compression.enabled: true
server.compression.mime-types: application/json,application/xml,text/html,text/xml,text/plain,text/css,application/javascript
After losing hours trying to find my error, the problem is your formula:
sigma = sum(y*(x-mean)**2)/n
This previous formula is wrong, the correct formula is the square root of this!;
sqrt(sum(y*(x-mean)**2)/n)
Hope this helps
Edit /etc/paths
. Then close the terminal and reopen it.
$ sudo vi /etc/paths
Note: each entry is seperated by line breaks.
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
You could use strcpy()
, like so:
strcpy(tab2, tmp.c_str());
Watch out for buffer overflow.
$(document).ready(function()
{
changeColor = $(.active).css("color","any color");
if($(".classname").hasClass('active')) {
$(this).eq(changeColor);
}
});
import pandas as pd
df = pd.DataFrame([{'Product': 'Coke', 'Prices': [100,123,101,105,99,94,98]},{'Product': 'Pepsi', 'Prices': [101,104,104,101,99,99,99]}])
print(df)
df = df.assign(Prices=df.Prices.str.split(',')).explode('Prices')
print(df)
Try this in pandas >=0.25 version
You can have a look at the EL (expression language) description here.
Both your code are correct, but I prefer the second one, as comparing a boolean to true
or false
is redundant.
For better readibility, you can also use the not
operator:
<c:if test="${not theBooleanVariable}">It's false!</c:if>
I faced the same issue. What I tried and worked for me:
Check the version of NODE and GULP (combination of node v12 and gulp less than v4 doesn't work)
I downgrade NPM version by:
It worked fine, then just follow instruction of your console.
Other Alternatives from just renaming the file to .doc.....
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word(office.11).aspx
Here is a good place to start. You can also try using this Office Open XML.
http://www.ecma-international.org/publications/standards/Ecma-376.htm
I have written a package in Golang which mimic the Python's range function:
Package https://github.com/thedevsaddam/iter
package main
import (
"fmt"
"github.com/thedevsaddam/iter"
)
func main() {
// sequence: 0-9
for v := range iter.N(10) {
fmt.Printf("%d ", v)
}
fmt.Println()
// output: 0 1 2 3 4 5 6 7 8 9
// sequence: 5-9
for v := range iter.N(5, 10) {
fmt.Printf("%d ", v)
}
fmt.Println()
// output: 5 6 7 8 9
// sequence: 1-9, increment by 2
for v := range iter.N(5, 10, 2) {
fmt.Printf("%d ", v)
}
fmt.Println()
// output: 5 7 9
// sequence: a-e
for v := range iter.L('a', 'e') {
fmt.Printf("%s ", string(v))
}
fmt.Println()
// output: a b c d e
}
Note: I have written for fun! Btw, sometimes it may be helpful
I ignore all classes residing in target folder from git. add following line in open .gitignore file:
/.class
OR
*/target/**
It is working perfectly for me. try it.
Various tools are available to you from within a shell. Sputnick has given you an excellent overview of your options, based on your initial question. He definitely deserves votes for the time he spent giving you multiple correct answers.
One more that's not on his list:
[ghoti@pc ~]$ dc -e '16i BFCA3000 p'
3217698816
But if all you want to do is subtract, why bother changing the input to base 10?
[ghoti@pc ~]$ dc -e '16i BFCA3000 17FF - p 10o p'
3217692673
BFCA1801
[ghoti@pc ~]$
The dc
command is "desk calc". It will also take input from stdin, like bc
, but instead of using "order of operations", it uses stacking ("reverse Polish") notation. You give it inputs which it adds to a stack, then give it operators that pop items off the stack, and push back on the results.
In the commands above we've got the following:
16i
-- tells dc to accept input in base 16 (hexadecimal). Doesn't change output base.BFCA3000
-- your initial number17FF
-- a random hex number I picked to subtract from your initial number-
-- take the two numbers we've pushed, and subtract the later one from the earlier one, then push the result back onto the stackp
-- print the last item on the stack. This doesn't change the stack, so...10o
-- tells dc to print its output in base "10", but remember that our input numbering scheme is currently hexadecimal, so "10" means "16".p
-- print the last item on the stack again ... this time in hex.You can construct fabulously complex math solutions with dc. It's a good thing to have in your toolbox for shell scripts.
find -L . -name "foo*"
In a few cases, I have needed the -L parameter to handle symbolic directory links. By default symbolic links are ignored. In those cases it was quite confusing as I would change directory to a sub-directory and see the file matching the pattern but find would not return the filename. Using -L solves that issue. The symbolic link options for find are -P -L -H
First argument in update
method is SyntheticEvent
object that contains common properties and methods to any event
, it is not reference to React component where there is property props
.
if you need pass argument to update method you can do it like this
onClick={ (e) => this.props.onClick(e, 'home', 'Home') }
and get these arguments inside update
method
update(e, space, txt){
console.log(e.target, space, txt);
}
event.target
gives you the native DOMNode
, then you need to use the regular DOM APIs to access attributes. For instance getAttribute
or dataset
<button
data-space="home"
className="home"
data-txt="Home"
onClick={ this.props.onClick }
/>
Button
</button>
onClick(e) {
console.log(e.target.dataset.txt, e.target.dataset.space);
}
It appears that my max ports weren't configured correctly. I ran the following code and it worked...
echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
What this command does is to increase the number of watches allowed for a single user. By the default the number can be low (8192 for example). When nodemon
tries to watch large numbers of directories for changes it has to create several watches, which can surpass that limit.
You could also solve this problem by:
sudo sysctl fs.inotify.max_user_watches=582222 && sudo sysctl -p
But the way it was written first will make this change permanent.
For me, this code looks more explicit:
CAST(@SomeDate AS datetime) + CAST(@SomeTime AS datetime)
Be sure to use the correct path!
I mistakenly had written C:\Program Files\Java\
. Changing it to C:\Program Files\Java\jdk\11.0.6\
fixed the issue.
In cmd
I then checked for the version of maven
with mvn -version
.
Try this
select * from test where Convert(varchar, date,111)= '03/19/2014'
Please check the ServerName which you provided. It should match with the below shown Name in the UserName textbox, and that name should followed with \SQLEXPRESS
:
This code is also working:
<html>_x000D_
<head></head>_x000D_
<body>_x000D_
_x000D_
<table style="table-layout:fixed;">_x000D_
<tr>_x000D_
<td style="word-break: break-all; width:100px;">ThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrap</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
</body></html>
_x000D_
This answer is only applicable for websites which uses Bootstrap. The responsive embed feature of the Bootstrap does the job. It is based on the width (not height) of the content.
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="http://www.youtube.com/embed/WsFWhL4Y84Y"></iframe>
</div>
jsfiddle: http://jsfiddle.net/00qggsjj/2/
pip install -U pip
pip install -U cython
Do you want to roll back your repo to that state, or you just want your local repo to look like that?
If you reset --hard
, it will make your local code and local history be just like it was at that commit. But if you wanted to push this to someone else who has the new history, it would fail:
git reset --hard c14809fa
And if you reset --soft
, it will move your HEAD to where they were , but leave your local files etc. the same:
git reset --soft c14809fa
So what exactly do you want to do with this reset?
Edit -
You can add "tags" to your repo.. and then go back to a tag. But a tag is really just a shortcut to the sha1.
You can tag this as TAG1.. then a git reset --soft c14809fa
, git reset --soft TAG1
, or git reset --soft c14809fafb08b9e96ff2879999ba8c807d10fb07
would all do the same thing.
Not sure what you are trying to accomplish on your first few lines but you can try this:
$(document).ready(function()
{
$("#ms_num").attr('maxlength','6');
});
Python is an interesting language in that while there is usually one (or two) "obvious" ways to accomplish any given task, flexibility still exists.
s = "string"
i = 0
print (s + repr(i))
The above code snippet is written in Python3 syntax but the parentheses after print were always allowed (optional) until version 3 made them mandatory.
Hope this helps.
Caitlin
A local variable is memory on the stack, that memory is not automatically invalidated when you go out of scope. From a Function deeper nested (higher on the stack in memory), its perfectly safe to access this memory.
Once the Function returns and ends though, things get dangerous. Usually the memory is not deleted or overwritten when you return, meaning the memory at that adresss is still containing your data - the pointer seems valid.
Until another function builds up the stack and overwrites it. This is why this can work for a while - and then suddenly cease to function after one particularly deeply nested set of functions, or a function with really huge sized or many local objects, reaches that stack-memory again.
It even can happen that you reach the same program part again, and overwrite your old local function variable with the new function variable. All this is very dangerous and should be heavily discouraged. Do not use pointers to local objects!
You could use linear-gradient
. Let's say the parent div
had a background image, and you needed a div
to sit on top of that with a gray background and a dog-eared left corner. You could do something like this:
.parent-div { background: url('/image.jpg'); }
.child-div {
background: #333;
background: linear-gradient(135deg, transparent 30px, #333 0);
}
Further reading:
You can also add a CALayer to the button - you can do lots of things with these including a color overlay, this example uses a plain color layer you can also easily graduate the colour. Be aware though added layers obscure those underneath
+(void)makeButtonColored:(UIButton*)button color1:(UIColor*) color
{
CALayer *layer = button.layer;
layer.cornerRadius = 8.0f;
layer.masksToBounds = YES;
layer.borderWidth = 4.0f;
layer.opacity = .3;//
layer.borderColor = [UIColor colorWithWhite:0.4f alpha:0.2f].CGColor;
CAGradientLayer *colorLayer = [CAGradientLayer layer];
colorLayer.cornerRadius = 8.0f;
colorLayer.frame = button.layer.bounds;
//set gradient colors
colorLayer.colors = [NSArray arrayWithObjects:
(id) color.CGColor,
(id) color.CGColor,
nil];
//set gradient locations
colorLayer.locations = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:1.0f],
nil];
[button.layer addSublayer:colorLayer];
}
I feel like this is the simplest way. (Feel free to change the width and height values).
<a href="http://www.google.com"
target="popup"
onclick="window.open('http://www.google.com','popup','width=600,height=600'); return false;">
Link Text goes here...
</a>
For VB.Net is
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "database path")
Dim cmd As New OleDb.OleDbCommand
Dim dt As New DataTable
Dim da As New OleDb.OleDbDataAdapter
con.Open()
cmd.Connection = con
cmd.CommandText = sql
da.SelectCommand = cmd
da.Fill(dt)
For i As Integer = 0 To dt.Rows.Count
someVar = dt.Rows(i)("fieldName")
Next