You can use Jquery's on method and listen for the scroll
event.
I experienced the same errors on a fresh install of VestaCP. I solved the issues by following the instructions on this video.
When you install the WAMPP in your machine by default the password of PhpMyAdmin is blank. so put root in user Section and left blank of password field. hope it works.
Happy Coding!!
Crystal Reports SP 19 does not support Visual Studio 2017. According to SAP they are targeting Visual Studio 2017 compatibility in SP 20 which is tentatively scheduled for June 2017.
You can do this:
app-routing-modules.ts:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PowerBoosterComponent } from './component/power-booster.component';
export const routes: Routes = [
{ path: 'pipeexamples',component: PowerBoosterComponent,
data:{ name:'shubham' } },
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
In this above route, I want to send data via a pipeexamples path to PowerBoosterComponent.So now I can receive this data in PowerBoosterComponent like this:
power-booster-component.ts
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';
@Component({
selector: 'power-booster',
template: `
<h2>Power Booster</h2>`
})
export class PowerBoosterComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
//this.route.snapshot.data['name']
console.log("Data via params: ",this.route.snapshot.data['name']);
}
}
So you can get the data by this.route.snapshot.data['name']
.
Another possibility is to use bit sets, for which there is at least one package or you can use the built-in big package. In this case, basically you need to define a way to convert your object to an index.
This advice is a variant of the "be as unspecific as possible regarding inputs and as specific as possible regarding outputs" rule of thumb.
Usually if you have a method that takes a plain non-null value, you can map it over the Optional
, so the plain version is strictly more unspecific regarding inputs. However there are a bunch of possible reasons why you would want to require an Optional
argument nonetheless:
Optional
Optional
if the given value is emptyOptional
is so awesome that whoever uses your API should be required to learn about it ;-)Another way of setting the default to the HTML web forms editor is:
File
> New
> File
HTML Page
Open
button there is a down arrowOpen With
HTML (Web Forms) Editor
Set as Default
OK
I had the same problem, after install the MS VS Community 2015, I didn't find the RDLC files neither the Report Viewer component, I solve the problem by going in the Control Panel (Windows) -> Programs -> Try to uninstall the MS VS Community and choose MODIFY
, in this moment you will be able to Check the Microsoft SQL Server Data Tools.
That is it!
The above error run the commend line\
please change the command $ node server it's working and server is started
I did what @gbero said, and I changed the Android version number that Studio uses from 22 to 17 and it works.
I am using the backwards compatibility to build for Android ver 22 but to target 17 (idk if that's correctly said, I am still trying to figure this app stuff out) so that triggered the backwards compatibility, which afaik is what the android.support.v7.*
is. This is probably a bug with their rendering code. Not sure if clearing the cache as suggested above was needed as rendering didn't work just after invalidating the cache, it started working after I changed the version to render. If I change back to version 22, the rendering breaks, if I switch back to 17, it works again.
I found that the new version of PhpMyAdmin put the 'config.inc.php' files in /var/lib/phpmyadmin/
I spend much time in the wrong dir (/usr/share) as this is where all the files also is located, but changes are not reflected.
After putting my settings in
/var/lib/phpmyadmin/config.inc.php
They worked
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
pip install pyqt5
for python3 for ubuntu
You should use getClassLoader()
method in your root
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("main.fxml"));
Use MouseClick event instead of Click
Swift 5 Easy Way Just CopyPaste and change what you want
let fullString = NSMutableAttributedString(string:"To start messaging contacts who have Talklo, tap ")
// create our NSTextAttachment
let image1Attachment = NSTextAttachment()
image1Attachment.image = UIImage(named: "chatEmoji")
image1Attachment.bounds = CGRect(x: 0, y: -8, width: 25, height: 25)
// wrap the attachment in its own attributed string so we can append it
let image1String = NSAttributedString(attachment: image1Attachment)
// add the NSTextAttachment wrapper to our full string, then add some more text.
fullString.append(image1String)
fullString.append(NSAttributedString(string:" at the right bottom of your screen"))
// draw the result in a label
self.lblsearching.attributedText = fullString
@wdavo is correct. The same is also true for functions.
If you override a base function, like Update, then in your subclass you need:
new void Update()
{
//do stufff
}
Without the new at the start of the function decleration you will get the warning flag.
In our case, beside changing ToolsVersion from 14.0 to 15.0 on .csproj projet file, as stated by Dominik Litschauer, we also had to install an updated version of MSBuild, since compilation is being triggered by a Jenkins job. After installing Build Tools for Visual Studio 2019, we had got MsBuild version 16.0 and all new C# features compiled ok.
Have a look at Styled Button it will surely help you. There are lots examples please search on INTERNET.
eg:style
<style name="Widget.Button" parent="android:Widget">
<item name="android:background">@drawable/red_dot</item>
</style>
you can use your selector instead of red_dot
red_dot:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<solid android:color="#f00"/>
<size android:width="55dip"
android:height="55dip"/>
</shape>
Button:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="49dp"
style="@style/Widget.Button"
android:text="Button" />
Update for anyone using PyQt5 with python 3.x:
.ui
file."C:\python\Lib\site-packages\PyQt5\pyuic5.bat" -x Trial.ui -o trial_gui.py
for cases where PyQt5 is not a path variable. The path in quotes " " represents where the pyuic5.bat
file is.This should work!
The complete code with version checking.
if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
// do stuff for iOS 7 and newer
[self.navigationController.navigationBar setBarTintColor:[UIColor yellowColor]];
}
else {
// do stuff for older versions than iOS 7
[self.navigationController.navigationBar setTintColor:[UIColor yellowColor]];
}
This Kotlin state machine library has PlantUML export feature, it is not integrated with Android Studio but it is easy to visualize state machine structure on PlantUML web site.
If you mean to create a new form when a button is clicked, the below code may be of some use to you:
private void settingsButton_Click(Object sender, EventArgs e)
{
// Create a new instance of the Form2 class
Form2 settingsForm = new Form2();
// Show the settings form
settingsForm.Show();
}
From here, you could also use the 'Show Dialog' method
Because the answer is no longer valid with a more stable version of angular, I am posting a newer solution.
PHP Page: session.php
if (!isset($_SESSION))
{
session_start();
}
$_SESSION['variable'] = "hello world";
$sessions = array();
$sessions['variable'] = $_SESSION['variable'];
header('Content-Type: application/json');
echo json_encode($sessions);
Send back only the session variables you want in Angular not all of them don't want to expose more than what is needed.
JS All Together
var app = angular.module('StarterApp', []);
app.controller("AppCtrl", ['$rootScope', 'Session', function($rootScope, Session) {
Session.then(function(response){
$rootScope.session = response;
});
}]);
app.factory('Session', function($http) {
return $http.get('/session.php').then(function(result) {
return result.data;
});
});
HTML
Inside your html you can reference your session
<html ng-app="StarterApp">
<body ng-controller="AppCtrl">
{{ session.variable }}
</body>
I had this problem recently using VS 2015 Update 3 for my WPF project in .NET 4.6.2. The copy of my project was in a network folder, I moved it locally and that solved the problem.
This may solve other sort of problems, as it looks like VS 2015 doesn't like network paths. Another issue that is a big problem for them is syncing git repositories if my project is in a network path, also solved by moving it locally.
Empty strings and nulls are fundamentally different. A null is an absence of a value and an empty string is a value that is empty.
The programming language making assumptions about the "value" of a variable, in this case an empty string, will be as good as initiazing the string with any other value that will not cause a null reference problem.
Also, if you pass the handle to that string variable to other parts of the application, then that code will have no ways of validating whether you have intentionally passed a blank value or you have forgotten to populate the value of that variable.
Another occasion where this would be a problem is when the string is a return value from some function. Since string is a reference type and can technically have a value as null and empty both, therefore the function can also technically return a null or empty (there is nothing to stop it from doing so). Now, since there are 2 notions of the "absence of a value", i.e an empty string and a null, all the code that consumes this function will have to do 2 checks. One for empty and the other for null.
In short, its always good to have only 1 representation for a single state. For a broader discussion on empty and nulls, see the links below.
https://softwareengineering.stackexchange.com/questions/32578/sql-empty-string-vs-null-value
iReports Custom Fields for columns (sum, average, etc)
Right-Click on Variables and click Create Variable
Click on the new variable
a. Notice the properties on the right
Rename the variable accordingly
Change the Value Class Name to the correct Data Type
a. You can search by clicking the 3 dots
Select the correct type of calculation
Change the Expression
a. Click the little icon
b. Select the column you are looking to do the calculation for
c. Click finish
Set Initial Value Expression to 0
Set the increment type to none
Set the Reset Type (usually report)
Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)
Select the new variable
Click finish
try with sticky jquery plugin
https://github.com/garand/sticky
<script src="jquery.js"></script>_x000D_
<script src="jquery.sticky.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
$("#sticker").sticky({topSpacing:0});_x000D_
});_x000D_
</script>
_x000D_
You can solve it just in 1 second!
just use this url:
http://127.0.0.1/phpmyadmin/
instead of
http://localhost/phpmyadmin/
try this css:
/* Show in default resolution screen*/
#container2 {
width: 960px;
position: relative;
margin:0 auto;
line-height: 1.4em;
}
/* If in mobile screen with maximum width 479px. The iPhone screen resolution is 320x480 px (except iPhone4, 640x960) */
@media only screen and (max-width: 479px){
#container2 { width: 90%; }
}
Here the demo: http://jsfiddle.net/ongisnade/CG9WN/
The filter design method in accepted answer is correct, but it has a flaw. SciPy bandpass filters designed with b, a are unstable and may result in erroneous filters at higher filter orders.
Instead, use sos (second-order sections) output of filter design.
from scipy.signal import butter, sosfilt, sosfreqz
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
sos = butter(order, [low, high], analog=False, btype='band', output='sos')
return sos
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
sos = butter_bandpass(lowcut, highcut, fs, order=order)
y = sosfilt(sos, data)
return y
Also, you can plot frequency response by changing
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)
to
sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)
What is the difference between Git and GitHub?
Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.
GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.
Is Git saving every repository locally (in the user's machine) and in GitHub?
No, it's only local. You can decide to push (publish) some branches on GitHub.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.
How does Git compare to a backup system such as Time Machine?
It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.
Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?
Yes, committing and pushing are both manual.
If are not collaborating and you are already using a backup system why would you use Git?
If you encounter an error between commits you can use the command git diff
to see the differences between the current code and the last working commit, helping you to locate your error.
You can also just go back to the last working commit.
If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.
You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.
Make sure you check gitimmersion.com.
I usually use float: left;
and add overflow: auto;
to solve the collapsing parent problem (as to why this works, overflow: auto
will expand the parent instead of adding scrollbars if you do not give it explicit height, overflow: hidden
works as well). Most of the vertical alignment needs I had are for one-line of text in menu bars, which can be solved using line-height
property. If I really need to vertical align a block element, I'd set an explicit height on the parent and the vertically aligned item, position absolute, top 50%, and negative margin.
The reason I don't use display: table-cell
is the way it overflows when you have more items than the site's width can handle. table-cell will force the user to scroll horizontally, while floats will wrap the overflow menu, making it still usable without the need for horizontal scrolling.
The best thing about float: left and overflow: auto is that it works all the way back to IE6 without hacks, probably even further.
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
You can remove it from the repo and commit the change.
git rm .idea/ -r --cached
git add -u .idea/
git commit -m "Removed the .idea folder"
After that, you can push it to the remote and every checkout/clone after that will be ok.
What is the target platform of your application? I think you should set the platform to x86
, do not set it to Any CPU
.
I assume that you use distinct like a method call on a list. You need to use the result of the query as datasource for your DropDownList, for example by materializing it via ToList
.
var distinctCategories = product
.Select(m => new {m.CategoryId, m.CategoryName})
.Distinct()
.ToList();
DropDownList1.DataSource = distinctCategories;
DropDownList1.DataTextField = "CategoryName";
DropDownList1.DataValueField = "CategoryId";
Another way if you need the real objects instead of the anonymous type with only few properties is to use GroupBy
with an anonymous type:
List<Product> distinctProductList = product
.GroupBy(m => new {m.CategoryId, m.CategoryName})
.Select(group => group.First()) // instead of First you can also apply your logic here what you want to take, for example an OrderBy
.ToList();
A third option is to use MoreLinq's DistinctBy
.
.NET has two CLRs 2.0 and 4.0. CLR 2.0 works till .NET framework 3.5. CLR 4.0 works from .NET 4.0 onwards. Its possible that your solution is using a different CLR than your reference assemblies. In your local development environment, you might have both the CLRs and hence you did not faced any problem. However when you moved to deployment environments, they might have a single CLR only and you got this error.
font-family: 'Open Sans'; font-weight: 600; important to change to a different font-family
You can use android:background="#DC143C"
, or any other RGB values for your color. I have no problem using it this way, as stated here
I had a similar issue however found a different solution than what I have read. I came to my fix after reading P Walker's answer.
My issue happened when I named my resource file for Japanese language incorrectly. Long story short I was trying to create a Resource for Japanese but I accidentally named it localized.jp.resx. I then realized that the iso language code is ja not jp for Japanese. Once I changed the file name to localized.ja.resx and deleted everything that was in the designer file it fixed my problem.
This is what fixed my problem hopefully it helps someone else.
Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following
#term-defs {
height: 300px;
overflow: scroll; }
This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.
#top {
position: fixed;
top: 0;
left: 0;
z-index: 999;
width: 100%;
height: 23px;
}
This will fix it to the top, on top of other content with a height of 23px.
The final implementation will depend on what effect you really want.
try http://code.google.com/p/swinghtmltemplate/
this will allow you to create gui with html-like syntax
You can use .NET 4's dynamic type and built-in JavaScriptSerializer to do that. Something like this, maybe:
string json = "{\"items\":[{\"Name\":\"AAA\",\"Age\":\"22\",\"Job\":\"PPP\"},{\"Name\":\"BBB\",\"Age\":\"25\",\"Job\":\"QQQ\"},{\"Name\":\"CCC\",\"Age\":\"38\",\"Job\":\"RRR\"}]}";
var jss = new JavaScriptSerializer();
dynamic data = jss.Deserialize<dynamic>(json);
StringBuilder sb = new StringBuilder();
sb.Append("<table>\n <thead>\n <tr>\n");
// Build the header based on the keys in the
// first data item.
foreach (string key in data["items"][0].Keys) {
sb.AppendFormat(" <th>{0}</th>\n", key);
}
sb.Append(" </tr>\n </thead>\n <tbody>\n");
foreach (Dictionary<string, object> item in data["items"]) {
sb.Append(" <tr>\n");
foreach (string val in item.Values) {
sb.AppendFormat(" <td>{0}</td>\n", val);
}
}
sb.Append(" </tr>\n </tbody>\n</table>");
string myTable = sb.ToString();
At the end, myTable
will hold a string that looks like this:
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Job</th>
</tr>
</thead>
<tbody>
<tr>
<td>AAA</td>
<td>22</td>
<td>PPP</td>
<tr>
<td>BBB</td>
<td>25</td>
<td>QQQ</td>
<tr>
<td>CCC</td>
<td>38</td>
<td>RRR</td>
</tr>
</tbody>
</table>
I had simply changed the capitalization of ONE character in one of my report parameters and could no longer deploy. Changing the single character back to uppercase allowed me to redeploy. Remarkable.
I found it was impossible to assign a layout to the centralwidget until I had added at least one child beneath it. Then I could highlight the tiny icon with the red 'disabled' mark and then click on a layout in the Designer toolbar at top.
I just spent an hour on a similar problem. For me the answer turned out to be embarrassingly simple.
(dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);
Code-first appears to be the rising star. I had a quick look at Ruby on Rails, and their standard is code-first, with database migrations.
If you are building an MVC3 application, I believe Code first has the following advantages:
Update
The question also asks for a comparison of code-first to EDMX model/db-first. Code-first can be used for both of these approaches too:
No, you can't edit the connection string in the designer. The connection string is not part of the EDMX file it is just referenced value from the configuration file and probably because of that it is just readonly in the properties window.
Modifying configuration file is common task because you sometimes wants to make change without rebuilding the application. That is the reason why configuration files exist.
Extension class:
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace MyProj.Extensions
{
public static class XmlExtension
{
public static string Serialize<T>(this T value)
{
if (value == null) return string.Empty;
var xmlSerializer = new XmlSerializer(typeof(T));
using (var stringWriter = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(stringWriter,new XmlWriterSettings{Indent = true}))
{
xmlSerializer.Serialize(xmlWriter, value);
return stringWriter.ToString();
}
}
}
}
}
Usage:
Foo foo = new Foo{MyProperty="I have been serialized"};
string xml = foo.Serialize();
Just reference the namespace holding your extension method in the file you would like to use it in and it'll work (in my example it would be: using MyProj.Extensions;
)
Note that if you want to make the extension method specific to only a particular class(eg., Foo
), you can replace the T
argument in the extension method, eg.
public static string Serialize(this Foo value){...}
I wanted to use an xml control file based on a class for my VB.net desktop WPF application. The above code to do this all in one is excellent and set me in the right direction. In case anyone is searching for a VB.net solution here is the class I built:
Imports System.IO
Imports System.Xml.Serialization
Public Class XControl
Private _person_ID As Integer
Private _person_UID As Guid
'load from file
Public Function XCRead(filename As String) As XControl
Using sr As StreamReader = New StreamReader(filename)
Dim xmls As New XmlSerializer(GetType(XControl))
Return CType(xmls.Deserialize(sr), XControl)
End Using
End Function
'save to file
Public Sub XCSave(filename As String)
Using sw As StreamWriter = New StreamWriter(filename)
Dim xmls As New XmlSerializer(GetType(XControl))
xmls.Serialize(sw, Me)
End Using
End Sub
'all the get/set is below here
Public Property Person_ID() As Integer
Get
Return _person_ID
End Get
Set(value As Integer)
_person_ID = value
End Set
End Property
Public Property Person_UID As Guid
Get
Return _person_UID
End Get
Set(value As Guid)
_person_UID = value
End Set
End Property
End Class
Try float
property. Here's an example: http://jsfiddle.net/mLmHR/
Once you have add your layout with at least one widget in it, select your window and click the "Update" button of QtDesigner. The interface will be resized at the most optimized size and your layout will fit the whole window. Then when resizing the window, the layout will be resized in the same way.
You should check out heroku_san, it solves this problem quite nicely.
For example, you could:
git checkout BRANCH
rake qa deploy
It also makes it easy to spin up new Heroku instances to deploy a topic branch to new servers:
git checkout BRANCH
# edit config/heroku.yml with new app instance and shortname
rake shortname heroku:create deploy # auto creates deploys and migrates
And of course you can make simpler rake tasks if you do something frequently.
I know this is a very old question, but I recently experienced the "cannot copy from obj to bin" error in VS 2012. Every single time I tried to rebuild a certain project, I got the message. The only solution was to do a clean before every rebuild.
After much investigating, it turns out I had an incomplete pragma warning statement in one of my files that did not prevent the compilation from succeeding, but was somehow confusing VS into keeping the file(s) locked.
In my case, I had the following at the top of the file:
#pragma warning(
That's it. I guess I was attempting to do something a while back and got distracted and never finished the process, but the VS warnings about that particular line were lost in the shuffle. Eventually I noticed the warning, removed the line, and rebuild works every time since then.
In order to compile .ui files to .py files, I did:
python pyuic.py form1.ui > form1.py
Att.
I figured it out. The problem was that there were still some pages in the project that hadn't been converted to use "namespaces" as needed in a web application project. I guess I thought that it wouldn't compile if there were still any of those pages around, but if the page didn't reference anything from outside itself it didn't appear to squawk. So when it was saying that it didn't inherit from "System.Web.UI.Page" that was because it couldn't actually find the class "BasePage" at run time because the page itself was not in the WebApplication namespace. I went through all my pages one by one and made sure that they were properly added to the WebApplication namespace and now it not only compiles without issue, it also displays normally. yay!
what a trial converting from website to web application project can be!
To get a scrollbar for an ItemsControl
, you can host it in a ScrollViewer
like this:
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl>
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
</ItemsControl>
</ScrollViewer>
Since cmp
has been removed, you can get the same functionality with
def cmp(a, b):
return (a > b) - (a < b)
def sign(a):
return (a > 0) - (a < 0)
It works for float
, int
and even Fraction
. In the case of float
, notice sign(float("nan"))
is zero.
Python doesn't require that comparisons return a boolean, and so coercing the comparisons to bool() protects against allowable, but uncommon implementation:
def sign(a):
return bool(a > 0) - bool(a < 0)
As an addendum: Before HTML 5 while a div inside a li is valid, a div inside a dl, dd, or dt is not!
click()
to the QMainWindow custom slot you have created).Code example:
MainWindow.h
// ...
include "newwindow.h"
// ...
public slots:
void openNewWindow();
// ...
private:
NewWindow *mMyNewWindow;
// ...
}
MainWindow.cpp
// ...
MainWindow::MainWindow()
{
// ...
connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
// ...
}
// ...
void MainWindow::openNewWindow()
{
mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
mMyNewWindow->show();
// ...
}
This is an example on how display a custom new window. There are a lot of ways to do this.
Drag a tooltip control from the toolbox onto your form. You don't really need to give it any properties other than a name. Then, in the properties of the control you wish to have a tooltip on, look for a new property with the name of the tooltip control you just added. It will by default give you a tooltip when the cursor hovers the control.
You also should set border:none
to that css class.
<ScrollViewer Height="239" VerticalScrollBarVisibility="Auto">
<TextBox AcceptsReturn="True" TextWrapping="Wrap" LineHeight="10" />
</ScrollViewer>
This is way to use the scrolling TextBox in XAML and use it as a text area.
I know of a much easier and less painful method:
$ git branch -m [branch_to_force_pull] tmp
$ git fetch
$ git checkout [branch_to_force_pull]
$ git branch -D tmp
That's it!
I was able to accomplish editing the default.aspx
page by:
By doing that I was able to remove the tagprefix causing a problem on my page.
Inline functions have special rules about what extern
means. (Note that inline functions are a C99 or GNU extension; they weren't in original C.
For non-inline functions, extern
is not needed as it is on by default.
Note that the rules for C++ are different. For example, extern "C"
is needed on the C++ declaration of C functions that you are going to call from C++, and there are different rules about inline
.
What you want to achieve by using class hierarchy can be achieved merely through namespacing. So languages that support namespapces ( like C#) will have no use of implementing class hierarchy of static classes. Since you can not instantiate any of the classes, all you need is a hierarchical organization of class definitions which you can obtain through the use of namespaces
With a .rdl, .rdlc or similar file selected, you can either:
Let's suppose static methods were allowed in interfaces: * They would force all implementing classes to declare that method. * Interfaces would usually be used through objects, so the only effective methods on those would be the non-static ones. * Any class which knows a particular interface could invoke its static methods. Hence a implementing class' static method would be called underneath, but the invoker class does not know which. How to know it? It has no instantiation to guess that!
Interfaces were thought to be used when working with objects. This way, an object is instantiated from a particular class, so this last matter is solved. The invoking class need not know which particular class is because the instantiation may be done by a third class. So the invoking class knows only the interface.
If we want this to be extended to static methods, we should have the possibility to especify an implementing class before, then pass a reference to the invoking class. This could use the class through the static methods in the interface. But what is the differente between this reference and an object? We just need an object representing what it was the class. Now, the object represents the old class, and could implement a new interface including the old static methods - those are now non-static.
Metaclasses serve for this purpose. You may try the class Class of Java. But the problem is that Java is not flexible enough for this. You can not declare a method in the class object of an interface.
This is a meta issue - when you need to do ass
..blah blah
anyway you have an easy workaround - making the method non-static with the same logic. But then you would have to first create an object to call the method.
Black Box Testing is a software testing method in which the internal structure/ design/ implementation of the item being tested is NOT known to the tester. White Box Testing is a software testing method in which the internal structure/ design/ implementation of the item being tested is known to the tester.
Oh my God. not need to do anything special. only in your post section do as follows:
$.post(yourURL,{ '': results})(function(e){ ...}
In server use this:
public ActionResult MethodName(List<yourViewModel> model){...}
this link help you to done ...
Here's another one for Silverlight. And a list of nice gradients to use.
Microsoft itself posted a KB article about this, and that article has a service pack that they claim fixes the problem. See below.
http://support.microsoft.com/kb/959417/
It took a while for the associated update to install itself, but once it did, I was able to run the Visual Studio setup successfully from the Add/Remove Programs control panel.
This is some of the things you can put into a message box. Enjoy
MessageBox.Show("Enter the text for the message box",
"Enter the name of the message box",
(Enter the button names e.g. MessageBoxButtons.YesNo),
(Enter the icon e.g. MessageBoxIcon.Question),
(Enter the default button e.g. MessageBoxDefaultButton.Button1)
More information can be found here
I'm in VS 2003 and none of these worked for me. What worked was to open the code at the top of the .vb page in the section labeled Web Form Designer Generated Code (the part that says not to edit there) and declare it there, where the system declared all the other controls. Bizzare.
In android studio add/change this line at the end of gradle.properties (Global Properties)
:
...
org.gradle.jvmargs=-XX\:MaxHeapSize\=1024m -Xmx1024m
if it doesn't work you can retry with bigger than 1024 heap size.
I use GWTDesigner http://www.instantiations.com/gwtdesigner/ which is not free but works well. Best of all, their customer support is top notch - very responsive.
You mentioned Python, have you considered Dabo?
That would avoid much of the grunt work in a custom app.
Suspended. The session is waiting for an event, such as I/O, to complete.
The app object is instantiated on creation of the Express server. It has a middleware stack that can be customized in app.configure()
(this is now deprecated in version 4.x).
To setup your middleware, you can invoke app.use(<specific_middleware_layer_here>)
for every middleware layer that you want to add (it can be generic to all paths, or triggered only on specific path(s) your server handles), and it will add onto your Express middleware stack. Middleware layers can be added one by one in multiple invocations of use
, or even all at once in series with one invocation.
See use
documentation for more details.
To give an example for conceptual understanding of Express Middleware, here is what my app middleware stack (app.stack) looks like when logging my app object to the console as JSON:
stack:
[ { route: '', handle: [Function] },
{ route: '', handle: [Function: static] },
{ route: '', handle: [Function: bodyParser] },
{ route: '', handle: [Function: cookieParser] },
{ route: '', handle: [Function: session] },
{ route: '', handle: [Function: methodOverride] },
{ route: '', handle: [Function] },
{ route: '', handle: [Function] } ]
As you might be able to deduce, I called app.use(express.bodyParser())
, app.use(express.cookieParser())
, etc, which added these express middleware 'layers' to the middleware stack. Notice that the routes are blank, meaning that when I added those middleware layers I specified that they be triggered on any route. If I added a custom middleware layer that only triggered on the path /user/:id
that would be reflected as a string in the route
field of that middleware layer object in the stack printout above.
Each layer is essentially adding a function that specifically handles something to your flow through the middleware.
E.g. by adding bodyParser
, you're ensuring your server handles incoming requests through the express middleware. So, now parsing the body of incoming requests is part of the procedure that your middleware takes when handling incoming requests -- all because you called app.use(bodyParser)
.
var getMatchingGroups = function(s) {
var r=/\((.*?)\)/g, a=[], m;
while (m = r.exec(s)) {
a.push(m[1]);
}
return a;
};
getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]
add an ALIAS
on the subquery,
SELECT COUNT(made_only_recharge) AS made_only_recharge
FROM
(
SELECT DISTINCT (identifiant) AS made_only_recharge
FROM cdr_data
WHERE CALLEDNUMBER = '0130'
EXCEPT
SELECT DISTINCT (identifiant) AS made_only_recharge
FROM cdr_data
WHERE CALLEDNUMBER != '0130'
) AS derivedTable -- <<== HERE
You can use Google guava as such:
ImmutableList<char> dirs = ImmutableList.of('+', '-', '*', '^');
You import the function from outside the main instance, and don't add it to the methods block. so the context of this
is not the vm.
Either do this:
ready() {
checkAuth.call(this)
}
or add the method to your methods first (which will make Vue bind this
correctly for you) and call this method:
methods: {
checkAuth: checkAuth
},
ready() {
this.checkAuth()
}
The [Flags]
attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators, for example:
var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue;
Note that the [Flags]
attribute doesn't enable this by itself - all it does is allow a nice representation by the .ToString()
method:
enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
[Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
...
var str1 = (Suits.Spades | Suits.Diamonds).ToString();
// "5"
var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString();
// "Spades, Diamonds"
It is also important to note that [Flags]
does not automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations, because by default the values start with 0 and increment.
Incorrect declaration:
[Flags]
public enum MyColors
{
Yellow, // 0
Green, // 1
Red, // 2
Blue // 3
}
The values, if declared this way, will be Yellow = 0, Green = 1, Red = 2, Blue = 3. This will render it useless as flags.
Here's an example of a correct declaration:
[Flags]
public enum MyColors
{
Yellow = 1,
Green = 2,
Red = 4,
Blue = 8
}
To retrieve the distinct values in your property, one can do this:
if (myProperties.AllowedColors.HasFlag(MyColor.Yellow))
{
// Yellow is allowed...
}
or prior to .NET 4:
if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow)
{
// Yellow is allowed...
}
if((myProperties.AllowedColors & MyColor.Green) == MyColor.Green)
{
// Green is allowed...
}
Under the covers
This works because you used powers of two in your enumeration. Under the covers, your enumeration values look like this in binary ones and zeros:
Yellow: 00000001
Green: 00000010
Red: 00000100
Blue: 00001000
Similarly, after you've set your property AllowedColors to Red, Green and Blue using the binary bitwise OR |
operator, AllowedColors looks like this:
myProperties.AllowedColors: 00001110
So when you retrieve the value you are actually performing bitwise AND &
on the values:
myProperties.AllowedColors: 00001110
MyColor.Green: 00000010
-----------------------
00000010 // Hey, this is the same as MyColor.Green!
The None = 0 value
And regarding the use of 0
in your enumeration, quoting from MSDN:
[Flags]
public enum MyColors
{
None = 0,
....
}
Use None as the name of the flag enumerated constant whose value is zero. You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set.
You can find more info about the flags attribute and its usage at msdn and designing flags at msdn
Well, basically what I found is that you can declare the array, but when you set it vba shows you an error.
So I put an special sub to declare global variables and arrays, something like:
Global example(10) As Variant
Sub set_values()
example(1) = 1
example(2) = 1
example(3) = 1
example(4) = 1
example(5) = 1
example(6) = 1
example(7) = 1
example(8) = 1
example(9) = 1
example(10) = 1
End Sub
And whenever I want to use the array, I call the sub first, just in case
call set_values
Msgbox example(5)
Perhaps is not the most correct way, but I hope it works for you
You have successfully removed the row names. The print.data.frame
method just shows the row numbers if no row names are present.
df1 <- data.frame(values = rnorm(3), group = letters[1:3],
row.names = paste0("RowName", 1:3))
print(df1)
# values group
#RowName1 -1.469809 a
#RowName2 -1.164943 b
#RowName3 0.899430 c
rownames(df1) <- NULL
print(df1)
# values group
#1 -1.469809 a
#2 -1.164943 b
#3 0.899430 c
You can suppress printing the row names and numbers in print.data.frame
with the argument row.names
as FALSE
.
print(df1, row.names = FALSE)
# values group
# -1.4345829 d
# 0.2182768 e
# -0.2855440 f
Edit: As written in the comments, you want to convert this to HTML. From the xtable
and print.xtable
documentation, you can see that the argument include.rownames
will do the trick.
library("xtable")
print(xtable(df1), type="html", include.rownames = FALSE)
#<!-- html table generated in R 3.1.0 by xtable 1.7-3 package -->
#<!-- Thu Jun 26 12:50:17 2014 -->
#<TABLE border=1>
#<TR> <TH> values </TH> <TH> group </TH> </TR>
#<TR> <TD align="right"> -0.34 </TD> <TD> a </TD> </TR>
#<TR> <TD align="right"> -1.04 </TD> <TD> b </TD> </TR>
#<TR> <TD align="right"> -0.48 </TD> <TD> c </TD> </TR>
#</TABLE>
shell_exec
- Execute command via shell and return the complete output as a string
exec
- Execute an external program.
The difference is that with shell_exec
you get output as a return value.
If I remember correctly (from a couple of years ago), one of the senior developers was talking about a fast way to bzero() on PowerPC (specs said we needed to zero almost all the memory on power up). It might not translate well (if at all) to x86, but it could be worth exploring.
The idea was to load a data cache line, clear that data cache line, and then write the cleared data cache line back to memory.
For what it is worth, I hope it helps.
Edited:
![system schema](doc/systemDiagram.jpg)
tree
+-- doc
+-- jobsSystemSchema.jpg
+-- README.md
markdown file README.md is at the same level as doc directory.
In your case ,your markdown file should be at the same level as the directory files.
![system schema](https://server/group/jobs/raw/master/doc/systemDiagram.jpg)
![system schema](https://server/group/jobs/blob/master/doc/systemDiagram.jpg)
DateTime does not know its timezone offset. There is no built-in method to return the offset or the timezone name (e.g. EAT, CEST, EST etc).
Like suggested by others, you can convert your date to UTC:
DateTime localtime = new DateTime.Now;
var utctime = localtime.ToUniversalTime();
and then only calculate the difference:
TimeSpan difference = localtime - utctime;
Also you may convert one time to another by using the DateTimeOffset:
DateTimeOffset targetTime = DateTimeOffset.Now.ToOffset(new TimeSpan(5, 30, 0));
But this is sort of lossy compression - the offset alone cannot tell you which time zone it is as two different countries may be in different time zones and have the same time only for part of the year (eg. South Africa and Europe). Also, be aware that summer daylight saving time may be introduced at different dates (EST vs CET - a 3-week difference).
You can get the name of your local system time zone using TimeZoneInfo class:
TimeZoneInfo localZone = TimeZoneInfo.Local;
localZone.IsDaylightSavingTime(localtime) ? localZone.DaylightName : localZone.StandardName
I agree with Gerrie Schenck, please read the article he suggested.
Because if you don't make a copy then the indices can still be manipulated elsewhere even if you assign the dataFrame to a different name.
For example:
df2 = df
func1(df2)
func2(df)
func1 can modify df by modifying df2, so to avoid that:
df2 = df.copy()
func1(df2)
func2(df)
Another (!) issue to worry about is the possible change of implementation between early/late versions of Java. I don't believe the implementation details are set in stone, and so potentially an upgrade to a future Java version could cause problems.
Bottom line is, I wouldn't rely on the implementation of hashCode()
.
Perhaps you can highlight what problem you're actually trying to solve by using this mechanism, and that will highlight a more suitable approach.
In my case, I read the registry that npm using:
npm config get registry
and I got
http://registry.npmjs.org/
then I had just changed http
to https
like this:
npm config set registry https://registry.npmjs.org/
I followed this tutorial, and everything is OK.
try this
<html>_x000D_
<head>_x000D_
<style type="text/css">_x000D_
body {_x000D_
font-family: sans-serif;_x000D_
font-size: 14px;_x000D_
}_x000D_
</style>_x000D_
_x000D_
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places®ion=in" type="text/javascript"></script>_x000D_
<script type="text/javascript">_x000D_
function initialize() {_x000D_
var input = document.getElementById('searchTextField');_x000D_
var autocomplete = new google.maps.places.Autocomplete(input);_x000D_
}_x000D_
google.maps.event.addDomListener(window, 'load', initialize);_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"
Change this to: "region=in" (in=india)
"http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places®ion=in" type="text/javascript"
I would use:
val, idx = min((val, idx) for (idx, val) in enumerate(my_list))
Then val
will be the minimum value and idx
will be its index.
For Each Sheet In Worksheets
If UCase(Sheet.Name) = "TEMP" Then
'Your Code when the match is True
Application.DisplayAlerts = False
Sheet.Delete
Application.DisplayAlerts = True
'-----------------------------------
End If
Next Sheet
Neither Glide nor Picasso is perfect. The way Glide loads an image to memory and do the caching is better than Picasso which let an image loaded far faster. In addition, it also helps preventing an app from popular OutOfMemoryError. GIF Animation loading is a killing feature provided by Glide. Anyway Picasso decodes an image with better quality than Glide.
Which one do I prefer? Although I use Picasso for such a very long time, I must admit that I now prefer Glide. But I would recommend you to change Bitmap Format to ARGB_8888 and let Glide cache both full-size image and resized one first. The rest would do your job great!
RGB_565
.+1 For Picasso Palette Helper.
There is a post that talk a lot about Picasso vs Glide post
In Mac OS X do this in the command prompt from the repo directory:
cd .git
rm index.lock
In Bootstrap 4:
class="font-weight-bold"
Or:
<strong>text</strong>
In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);
foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
Console.WriteLine(sub_obj.Key);
}
I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).
I think the parsing works according to the following principles:
Every object is abstracted as a JToken
Cast to JObject where you expect a Dictionary
Cast to JValue if the JToken represents a terminal node and is a value
Cast to JArray if its an array
JValue.Value gives you the .NET type you need
You have two options.
<colspan>
in your header to stretch a cell for two or more columns.<table>
with 2 columns inside the td
you want extra columns in.Not quite perfect, but it got me closer than some of the top answers here.
Two different tables, one with the header, and the other, wrapped with a div with the content
<table>
<thead>
<tr><th>Stuff</th><th>Second Stuff</th></tr>
</thead>
</table>
<div style="height: 600px; overflow: auto;">
<table>
<tbody>
//Table
</tbody>
</table>
</div>
I added a "Height" to my ListBox and it added the scrollbar nicely.
Because it is asynchronous, the $scope
is getting the data before the ajax call is complete.
You could use $q
in your service to create promise
and give it back to
controller, and controller obtain the result within then()
call against promise
.
In your service,
app.factory('myService', function($http, $q) {
var deffered = $q.defer();
var data = [];
var myService = {};
myService.async = function() {
$http.get('test.json')
.success(function (d) {
data = d;
console.log(d);
deffered.resolve();
});
return deffered.promise;
};
myService.data = function() { return data; };
return myService;
});
Then, in your controller:
app.controller('MainCtrl', function( myService,$scope) {
myService.async().then(function() {
$scope.data = myService.data();
});
});
InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
This is an expansion to totem's answer. It does basically the same thing but the property matching is based on the serialized json object, not reflect the .net object. This is important if you're using [JsonProperty], using the CamelCasePropertyNamesContractResolver, or doing anything else that will cause the json to not match the .net object.
Usage is simple:
[KnownType(typeof(B))]
public class A
{
public string Name { get; set; }
}
public class B : A
{
public string LastName { get; set; }
}
Converter code:
/// <summary>
/// Use KnownType Attribute to match a divierd class based on the class given to the serilaizer
/// Selected class will be the first class to match all properties in the json object.
/// </summary>
public class KnownTypeConverter : JsonConverter {
public override bool CanConvert( Type objectType ) {
return System.Attribute.GetCustomAttributes( objectType ).Any( v => v is KnownTypeAttribute );
}
public override bool CanWrite {
get { return false; }
}
public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer ) {
// Load JObject from stream
JObject jObject = JObject.Load( reader );
// Create target object based on JObject
System.Attribute[ ] attrs = System.Attribute.GetCustomAttributes( objectType ); // Reflection.
// check known types for a match.
foreach( var attr in attrs.OfType<KnownTypeAttribute>( ) ) {
object target = Activator.CreateInstance( attr.Type );
JObject jTest;
using( var writer = new StringWriter( ) ) {
using( var jsonWriter = new JsonTextWriter( writer ) ) {
serializer.Serialize( jsonWriter, target );
string json = writer.ToString( );
jTest = JObject.Parse( json );
}
}
var jO = this.GetKeys( jObject ).Select( k => k.Key ).ToList( );
var jT = this.GetKeys( jTest ).Select( k => k.Key ).ToList( );
if( jO.Count == jT.Count && jO.Intersect( jT ).Count( ) == jO.Count ) {
serializer.Populate( jObject.CreateReader( ), target );
return target;
}
}
throw new SerializationException( string.Format( "Could not convert base class {0}", objectType ) );
}
public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer ) {
throw new NotImplementedException( );
}
private IEnumerable<KeyValuePair<string, JToken>> GetKeys( JObject obj ) {
var list = new List<KeyValuePair<string, JToken>>( );
foreach( var t in obj ) {
list.Add( t );
}
return list;
}
}
You can use lambda expression like this.
int index = listOfElements.FindIndex(item => item.Id == id);
if (index != -1)
{
listOfElements[index] = newValue;
}
shell request failed on channel 0
mean you don't have shell or remote commands access, fix your user permission on server to have shell access or if you just want tunneling use -N
and -T
options
I think it's best to call join() on your threads when you expect them to die. I've taken some liberty with your code to make the loops end (you can add whatever cleanup needs are required to there as well). The variable die is checked for truth on each pass and when it's True then the program exits.
import threading
import time
class MyThread (threading.Thread):
die = False
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run (self):
while not self.die:
time.sleep(1)
print (self.name)
def join(self):
self.die = True
super().join()
if __name__ == '__main__':
f = MyThread('first')
f.start()
s = MyThread('second')
s.start()
try:
while True:
time.sleep(2)
except KeyboardInterrupt:
f.join()
s.join()
Right after our long comment section, I think this is what you're looking for, it's jQuery based:
HTML:
<img width="100%" id="img" src="http://uploads8.wikipaintings.org/images/william-adolphe-bouguereau/self-portrait-presented-to-m-sage-1886.jpg">
JS:
<script type="text/javascript">
window.onload = function(){
var img = document.getElementById('img')
if(img.clientHeight<$(window).height()){
img.style.height=$(window).height()+"px";
}
if(img.clientWidth<$(window).width()){
img.style.width=$(window).width()+"px";
}
}
?</script>??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
CSS:
body{
overflow: hidden;
}
?The code above is using the browsers width and height if you where doing this within a div, you would have to change it to something like this:
For Div:
HTML:
<div style="width:100px; max-height: 100px;" id="div">
<img width="100%" id="img" src="http://uploads8.wikipaintings.org/images/william-adolphe-bouguereau/self-portrait-presented-to-m-sage-1886.jpg">
</div>
JS:
<script type="text/javascript">
window.onload = function(){
var img = document.getElementById('img')
if(img.clientHeight<$('#div').height()){
img.style.height=$('#div').height()+"px";
}
if(img.clientWidth<$('#div').width()){
img.style.width=$('#div').width()+"px";
}
}
?</script>????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
CSS:
div{
overflow: hidden;
}
I should also state that I've only tested this is Google Chrome... here is a jsfiddle: http://jsfiddle.net/ADCKk/
Similar to Matthew's answer, I just found that you can do the following:
$(this).closest('form').submit();
Wrong: The problem with using the parent functionality is that the field needs to be immediately within the form to work (not inside tds, labels, etc).
I stand corrected: parents (with an s) also works. Thxs Paolo for pointing that out.
Just try to add exit;
at the end of your PHP script.
The Java EE version of Eclipse is not installed, insted a standard SDK version is installed.
You can go to Help > Install New Software then select the Eclipse site from the dropdown (Helios, Kepler depending upon your revision). Then select the option that shows Java EE. Restart Eclipse and you should see the Server list, such as Apache, Oracle, IBM etc.
Simpler, shorter, faster: EXISTS
.
IF EXISTS (SELECT 1 FROM people p WHERE p.person_id = my_person_id) THEN
-- do something
END IF;
The query planner can stop at the first row found - as opposed to count()
, which will scan all matching rows regardless. Makes a difference with big tables. Hardly matters with a condition on a unique column - only one row qualifies anyway (and there is an index to look it up quickly).
Improved with input from @a_horse_with_no_name in the comments below.
You could even use an empty SELECT
list:
IF EXISTS (SELECT FROM people p WHERE p.person_id = my_person_id) THEN ...
Since the SELECT
list is not relevant to the outcome of EXISTS
. Only the existence of at least one qualifying row matters.
Based on this guide for Mercurial my .gitignore includes:
.DS_Store
*.swp
*~.nib
build/
*.pbxuser
*.perspective
*.perspectivev3
I've also chosen to include:
*.mode1v3
*.mode2v3
which, according to this Apple mailing list post, are "user-specific project settings".
And for Xcode 4:
xcuserdata
element: HTMLElement;
constructor() {}
fakeClick(){
this.element = document.getElementById('ButtonX') as HTMLElement;
this.element.click();
}
Noone cand read the file except for those who have access to the file. You must make the code readable (but not writable) by the web server. If the php code handler is running properly you can't read it by requesting by name from the web server.
If someone compromises your server you are at risk. Ensure that the web server can only write to locations it absolutely needs to. There are a few locations under /var which should be properly configured by your distribution. They should not be accessible over the web. /var/www should not be writable, but may contain subdirectories written to by the web server for dynamic content. Code handlers should be disabled for these.
Ensure you don't do anything in your php code which can lead to code injection. The other risk is directory traversal using paths containing .. or begining with /. Apache should already be patched to prevent this when it is handling paths. However, when it runs code, including php, it does not control the paths. Avoid anything that allows the web client to pass a file path.
As a service
You can set this one by:
Going first to your installation directory (in my case it’s c:\xampplite
). It could be somewhere else depending on your installation. Have also my full version in c:\x2\xampp
.
Once your in the installation directory, find xampp-control.exe
and click/double-click to launch it.
You should first stop all running instances of your apache2
and mysqld
/mysql
processes to do this.
Click the checkmark next to Apache and MySQL with the header name service. It will warn you that it’s installing as a service which of course is what we like it to do. Click Yes.
Also do step 5 with MySQL. We’re almost done.
Click Start ? Run
Type services.msc (it can also be done in the control panel under administrative tools which is a way lot of click than this one). Find the Apache 2 and MySQL services.
Double click each one and set the startup type to Automatic (you will be presented with three options: Automatic, Manual, and Disabled):
net start apache2
Be warned though that any change in the services just like the registry can cause your system to stall.
Click the start button to manually start it (just for the session though). At the next restart it’ll be automated.
Do the same with MySQL.
As a startup program
Find xampp_start.exe from your installation directory.
Press Ctrl + C to copy it or right-click the file and hit copy.
Go to C:\Documents and Settings\Administrator\Start Menu\Programs\Startup and right click on it and hit Paste Shortcut.
When you restart it’ll be starting also and you’ll see something like this:
You can stop it by issuing the xampp_stop.exe
command in your installation directory.
Also worth mentioning is that if you right click again on the shortcut and hit properties, try to change the run option to minimized. This way the shortcut will be on your taskbar once started.
Inspired from Robert's answer, but when we use,
ng-click="searchAll = null"
in the filter, it makes the model values as null
and in-turn the search doesn't work with its normal functionality, so it would be better enough to use ng-click="searchAll = ''"
instead
You can make sure that the object in question is stringified before passing it to parse function by simply using JSON.stringify()
.
Updated your line below,
JSON.parse(JSON.stringify({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false}));
or if you have JSON stored in some variable:
JSON.parse(JSON.stringify(yourJSONobject));
Unless you want to talk to an SMTP server directly via telnet
you'd use commandline mailers like blat
:
blat -to [email protected] -f [email protected] -s "mail subject" ^
-server smtp.example.net -body "message text"
or bmail
:
bmail -s smtp.example.net -t [email protected] -f [email protected] -h ^
-a "mail subject" -b "message text"
You could also write your own mailer in VBScript or PowerShell.
You can call a reset function before appending. Something like this:
function resetNewReviewBoardForm() {
$("#Description").val('');
$("#PersonName").text('');
$("#members").empty(); //this one what worked in my case
$("#EmailNotification").val('False');
}
Most probably you may have not installed maven correctly.
use this to download maven. Download the latest (Binary tar.gz)
file.It worked for me.
Use the TimeSpan object to capture your initial time element and use the methods such as AddHours
or AddMinutes
. To substract 3 hours, you will do AddHours(-3)
. To substract 45 mins, you will do AddMinutes(-45)
To reduce verbosity, you can use a static import:
import static java.util.concurrent.TimeUnit.NANOSECONDS;
-and henceforth just type
NANOSECONDS.toSeconds(elapsedTime);
JPA specification contains a very precise description of semantics of these operations, better than in javadoc:
The semantics of the persist operation, applied to an entity X are as follows:
If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.
If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the
cascade=PERSIST
orcascade=ALL
annotation element value or specified with the equivalent XML descriptor element.If X is a removed entity, it becomes managed.
If X is a detached object, the
EntityExistsException
may be thrown when the persist operation is invoked, or theEntityExistsException
or anotherPersistenceException
may be thrown at flush or commit time.For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value
cascade=PERSIST
orcascade=ALL
, the persist operation is applied to Y.
The semantics of the merge operation applied to an entity X are as follows:
If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.
If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.
If X is a removed entity instance, an
IllegalArgumentException
will be thrown by the merge operation (or the transaction commit will fail).If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value
cascade=MERGE
orcascade=ALL
annotation.For all entities Y referenced by relationships from X having the cascade element value
cascade=MERGE
orcascade=ALL
, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)If X is an entity merged to X', with a reference to another entity Y, where
cascade=MERGE
orcascade=ALL
is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.
Try this. It's helped me to change from ConstraintLayout
to RelativeLayout
.
I like this:
"scripts": {
"??? Jenkins Build - in this order ??? ": "",
"purge": "lerna run something",
"clean:test": "lerna exec --ignore nanana"
}
There are extra spaces in the command name, so in Visual Studio Code's NPM Scripts plugin you have a better look.
I found it's better to set the width
and height
to 0px
. Otherwise, IE10 ignores the padding defined on the field -- padding-right
-- which was intended to keep the text from typing over the 'X' icon that I overlayed on the input field. I'm guessing that IE10 is internally applying the padding-right
of the input to the ::--ms-clear
pseudo element, and hiding the pseudo element does not restore the padding-right
value to the input
.
This worked better for me:
.someinput::-ms-clear {
width : 0;
height: 0;
}
You can copy subscribers dictionary object to a same type of temporary dictionary object and then iterate the temporary dictionary object using foreach loop.
statement level trigger is only once for dml statement row leval trigger is for each row for dml statements
.NET 3.5 and newer have a new public type, System.Data.Linq.Binary
that encapsulates byte[]
. It implements IEquatable<Binary>
that (in effect) compares two byte arrays. Note that System.Data.Linq.Binary
also has implicit conversion operator from byte[]
.
MSDN documentation:System.Data.Linq.Binary
Reflector decompile of the Equals method:
private bool EqualsTo(Binary binary)
{
if (this != binary)
{
if (binary == null)
{
return false;
}
if (this.bytes.Length != binary.bytes.Length)
{
return false;
}
if (this.hashCode != binary.hashCode)
{
return false;
}
int index = 0;
int length = this.bytes.Length;
while (index < length)
{
if (this.bytes[index] != binary.bytes[index])
{
return false;
}
index++;
}
}
return true;
}
Interesting twist is that they only proceed to byte-by-byte comparison loop if hashes of the two Binary objects are the same. This, however, comes at the cost of computing the hash in constructor of Binary
objects (by traversing the array with for
loop :-) ).
The above implementation means that in the worst case you may have to traverse the arrays three times: first to compute hash of array1, then to compute hash of array2 and finally (because this is the worst case scenario, lengths and hashes equal) to compare bytes in array1 with bytes in array 2.
Overall, even though System.Data.Linq.Binary
is built into BCL, I don't think it is the fastest way to compare two byte arrays :-|.
If you are trying to serve an HTML file which ALREADY has all it's content inside it, then it does not need to be 'rendered', it just needs to be 'served'. Rendering is when you have the server update or inject content before the page is sent to the browser, and it requires additional dependencies like ejs, as the other answers show.
If you simply want to direct the browser to a file based on their request, you should use res.sendFile() like this:
const express = require('express');
const app = express();
var port = process.env.PORT || 3000; //Whichever port you want to run on
app.use(express.static('./folder_with_html')); //This ensures local references to cs and js files work
app.get('/', (req, res) => {
res.sendFile(__dirname + '/folder_with_html/index.html');
});
app.listen(port, () => console.log("lifted app; listening on port " + port));
This way you don't need additional dependencies besides express. If you just want to have the server send your already created html files, the above is a very lightweight way to do so.
All providers work the same way. The different methods service
, factory
, provider
just let you accomplish the same thing in less code.
P.S. There's also value
and constant
.
Each special case down the chain starting with provider
and ending with value
has an added limitation. So to decide between them you have to ask yourself which let's you accomplish what you want with less code.
Here is a picture that shows you what I mean:
You can a breakdown and reference guide on the blog post I got this image from:
Pass the datable to this method it would return json String.
public DataTable GetTable()
{
string str = "Select * from GL_V";
OracleCommand cmd = new OracleCommand(str, con);
cmd.CommandType = CommandType.Text;
DataTable Dt = OracleHelper.GetDataSet(con, cmd).Tables[0];
return Dt;
}
public string DataTableToJSONWithJSONNet(DataTable table)
{
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(table);
return JSONString;
}
public static DataSet GetDataSet(OracleConnection con, OracleCommand cmd)
{
// create the data set
DataSet ds = new DataSet();
try
{
//checking current connection state is open
if (con.State != ConnectionState.Open)
con.Open();
// create a data adapter to use with the data set
OracleDataAdapter da = new OracleDataAdapter(cmd);
// fill the data set
da.Fill(ds);
}
catch (Exception ex)
{
throw;
}
return ds;
}
For those who want the textview to actually move up and maintain the bottom line position
CGRect frame = textView.frame;
frame.size.height = textView.contentSize.height;
if(frame.size.height > textView.frame.size.height){
CGFloat diff = frame.size.height - textView.frame.size.height;
textView.frame = CGRectMake(0, textView.frame.origin.y - diff, textView.frame.size.width, frame.size.height);
}
else if(frame.size.height < textView.frame.size.height){
CGFloat diff = textView.frame.size.height - frame.size.height;
textView.frame = CGRectMake(0, textView.frame.origin.y + diff, textView.frame.size.width, frame.size.height);
}
Thank you Guys to give me many suggestions. Finally I got a solution. That is i have started the NetErrorPage intent two times. One time, i have checked the net connection availability and started the intent in page started event. second time, if the page has error, then i have started the intent in OnReceivedError event. So the first time dialog is not closed, before that the second dialog is called. So that i got a error.
Reason for the Error: I have called the showInfoMessageDialog method two times before closing the first one.
Now I have removed the second call and Cleared error :-).
With Apache Commons Library, you can simply use Stringutils.replaceEach:
public static String replaceEach(String text,
String[] searchList,
String[] replacementList)
From the documentation:
Replaces all occurrences of Strings within another String.
A null reference passed to this method is a no-op, or if any "search string" or "string to replace" is null, that replace will be ignored. This will not repeat. For repeating replaces, call the overloaded method.
StringUtils.replaceEach(null, *, *) = null
StringUtils.replaceEach("", *, *) = ""
StringUtils.replaceEach("aba", null, null) = "aba"
StringUtils.replaceEach("aba", new String[0], null) = "aba"
StringUtils.replaceEach("aba", null, new String[0]) = "aba"
StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba"
StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b"
StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba"
StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
(example of how it does not repeat)
StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte"
In Oracle, you can do:
SELECT *
FROM (SELECT EMP.*,ROWNUM FROM EMP ORDER BY ROWNUM DESC)
WHERE ROWNUM=1;
This is one of the possible ways.
String s = "ABC[This is to extract]";
System.out.println(s);
int startIndex = s.indexOf('[');
System.out.println("indexOf([) = " + startIndex);
int endIndex = s.indexOf(']');
System.out.println("indexOf(]) = " + endIndex);
System.out.println(s.substring(startIndex + 1, endIndex));
i think you have only defined the function. you are not triggering it anywhere.
please do
window.onload = addList();
or trigger it on some other event
after its definition
see this fiddle
This is a typical case of java.lang.StackOverflowError
... The method is recursively calling itself with no exit in doubleValue()
, floatValue()
, etc.
public class Rational extends Number implements Comparable<Rational> {
private int num;
private int denom;
public Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
public int compareTo(Rational r) {
if ((num / denom) - (r.num / r.denom) > 0) {
return +1;
} else if ((num / denom) - (r.num / r.denom) < 0) {
return -1;
}
return 0;
}
public Rational add(Rational r) {
return new Rational(num + r.num, denom + r.denom);
}
public Rational sub(Rational r) {
return new Rational(num - r.num, denom - r.denom);
}
public Rational mul(Rational r) {
return new Rational(num * r.num, denom * r.denom);
}
public Rational div(Rational r) {
return new Rational(num * r.denom, denom * r.num);
}
public int gcd(Rational r) {
int i = 1;
while (i != 0) {
i = denom % r.denom;
denom = r.denom;
r.denom = i;
}
return denom;
}
public String toString() {
String a = num + "/" + denom;
return a;
}
public double doubleValue() {
return (double) doubleValue();
}
public float floatValue() {
return (float) floatValue();
}
public int intValue() {
return (int) intValue();
}
public long longValue() {
return (long) longValue();
}
}
public class Main {
public static void main(String[] args) {
Rational a = new Rational(2, 4);
Rational b = new Rational(2, 6);
System.out.println(a + " + " + b + " = " + a.add(b));
System.out.println(a + " - " + b + " = " + a.sub(b));
System.out.println(a + " * " + b + " = " + a.mul(b));
System.out.println(a + " / " + b + " = " + a.div(b));
Rational[] arr = {new Rational(7, 1), new Rational(6, 1),
new Rational(5, 1), new Rational(4, 1),
new Rational(3, 1), new Rational(2, 1),
new Rational(1, 1), new Rational(1, 2),
new Rational(1, 3), new Rational(1, 4),
new Rational(1, 5), new Rational(1, 6),
new Rational(1, 7), new Rational(1, 8),
new Rational(1, 9), new Rational(0, 1)};
selectSort(arr);
for (int i = 0; i < arr.length - 1; ++i) {
if (arr[i].compareTo(arr[i + 1]) > 0) {
System.exit(1);
}
}
Number n = new Rational(3, 2);
System.out.println(n.doubleValue());
System.out.println(n.floatValue());
System.out.println(n.intValue());
System.out.println(n.longValue());
}
public static <T extends Comparable<? super T>> void selectSort(T[] array) {
T temp;
int mini;
for (int i = 0; i < array.length - 1; ++i) {
mini = i;
for (int j = i + 1; j < array.length; ++j) {
if (array[j].compareTo(array[mini]) < 0) {
mini = j;
}
}
if (i != mini) {
temp = array[i];
array[i] = array[mini];
array[mini] = temp;
}
}
}
}
2/4 + 2/6 = 4/10
Exception in thread "main" java.lang.StackOverflowError
2/4 - 2/6 = 0/-2
at com.xetrasu.Rational.doubleValue(Rational.java:64)
2/4 * 2/6 = 4/24
at com.xetrasu.Rational.doubleValue(Rational.java:64)
2/4 / 2/6 = 12/8
at com.xetrasu.Rational.doubleValue(Rational.java:64)
at com.xetrasu.Rational.doubleValue(Rational.java:64)
at com.xetrasu.Rational.doubleValue(Rational.java:64)
at com.xetrasu.Rational.doubleValue(Rational.java:64)
at com.xetrasu.Rational.doubleValue(Rational.java:64)
AngularJS's Filter worked out for me.
Assuming the code/id
is unique, we can filter out that particular object with AngularJS's filter
and work with the selected objects properties. Considering the example above:
<select ng-options="size.code as size.name for size in sizes"
ng-model="item.size.code"
ng-change="update(MAGIC_THING); search.code = item.size.code">
</select>
<!-- OUTSIDE THE SELECT BOX -->
<h1 ng-repeat="size in sizes | filter:search:true"
ng-init="search.code = item.size.code">
{{size.name}}
</h1>
Now, there are 3 important aspects to this:
ng-init="search.code = item.size.code"
- on initializing h1
element outside select
box, set the filter query to the selected option.
ng-change="update(MAGIC_THING); search.code = item.size.code"
- when you change the select input, we'll run one more line which will set the "search" query to the currently selected item.size.code
.
filter:search:true
- Pass true
to filter to enable strict matching.
That's it. If the size.code
is uniqueID, we'll have only one h1
element with the text of size.name
.
I've tested this in my project and it works.
Good Luck
First of all you should stop using mysql_*. MySQL supports multiple inserting like
INSERT INTO example
VALUES
(100, 'Name 1', 'Value 1', 'Other 1'),
(101, 'Name 2', 'Value 2', 'Other 2'),
(102, 'Name 3', 'Value 3', 'Other 3'),
(103, 'Name 4', 'Value 4', 'Other 4');
You just have to build one string in your foreach loop which looks like that
$values = "(100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1')";
and then insert it after the loop
$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) VALUES ".$values;
Another way would be Prepared Statements, which are even more suited for your situation.
/dev/tty
is a synonym for the controlling terminal (if any) of the current process. As jtl999 says, it's a character special file; that's what the c
in the ls -l
output means.
man 4 tty
or man -s 4 tty
should give you more information, or you can read the man page online here.
Incidentally, pwd > /dev/tty
doesn't necessarily print to the shell's stdout (though it is the pwd
command's standard output). If the shell's standard output has been redirected to something other than the terminal, /dev/tty
still refers to the terminal.
You can also read from /dev/tty
, which will normally read from the keyboard.
To read a line from a file, you should use the fgets
function: It reads a string from the specified file up to either a newline character or EOF
.
The use of sscanf
in your code would not work at all, as you use filename
as your format string for reading from line
into a constant string literal %s
.
The reason for SEGV is that you write into the non-allocated memory pointed to by line
.
Finally i found my problem. SQL Reporting Service was causing my account lockout. Stop and try, after confirm no more passwords bad attempts i should reconfigure reporting services service account ---Not at Service Properties, it is in Reporting Service own config--.
Here's a more portable version (just for fun, it is not necessary in your case):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE, STDOUT
try:
from subprocess import DEVNULL # py3k
except ImportError:
import os
DEVNULL = open(os.devnull, 'wb')
text = u"René Descartes"
p = Popen(['espeak', '-b', '1'], stdin=PIPE, stdout=DEVNULL, stderr=STDOUT)
p.communicate(text.encode('utf-8'))
assert p.returncode == 0 # use appropriate for your program error handling here
$(document).on( "keydown", keyPressed);
function keyPressed (e){
e = e || window.e;
var newchar = e.which || e.keyCode;
alert(newchar)
}
Apart from answering OP's queries, Let me throw some insights on Apache Solr from simple introduction to detailed installation and implementation.
Simple Introduction
Anyone who has had experience with the search engines above, or other engines not in the list -- I would love to hear your opinions.
Solr shouldn't be used to solve real-time problems. For search engines, Solr is pretty much game and works flawlessly.
Solr works fine on High Traffic web-applications (I read somewhere that it is not suited for this, but I am backing up that statement). It utilizes the RAM, not the CPU.
- result relevance and ranking
The boost helps you rank your results show up on top. Say, you're trying to search for a name john in the fields firstname and lastname, and you want to give relevancy to the firstname field, then you need to boost up the firstname field as shown.
http://localhost:8983/solr/collection1/select?q=firstname:john^2&lastname:john
As you can see, firstname field is boosted up with a score of 2.
More on SolrRelevancy
- searching and indexing speed
The speed is unbelievably fast and no compromise on that. The reason I moved to Solr.
Regarding the indexing speed, Solr can also handle JOINS from your database tables. A higher and complex JOIN do affect the indexing speed. However, an enormous RAM config can easily tackle this situation.
The higher the RAM, The faster the indexing speed of Solr is.
- ease of use and ease of integration with Django
Never attempted to integrate Solr and Django, however you can achieve to do that with Haystack. I found some interesting article on the same and here's the github for it.
- resource requirements - site will be hosted on a VPS, so ideally the search engine wouldn't require a lot of RAM and CPU
Solr breeds on RAM, so if the RAM is high, you don't to have to worry about Solr.
Solr's RAM usage shoots up on full-indexing if you have some billion records, you could smartly make use of Delta imports to tackle this situation. As explained, Solr is only a near real-time solution.
- scalability
Solr is highly scalable. Have a look on SolrCloud. Some key features of it.
- extra features such as "did you mean?", related searches, etc
For the above scenario, you could use the SpellCheckComponent that is packed up with Solr. There are a lot other features, The SnowballPorterFilterFactory helps to retrieve records say if you typed, books instead of book, you will be presented with results related to book.
This answer broadly focuses on Apache Solr & MySQL. Django is out of scope.
Assuming that you are under LINUX environment, you could proceed to this article further. (mine was an Ubuntu 14.04 version)
Detailed Installation
Download Apache Solr from here. That would be version is 4.8.1. You could download new versions, I found this stable.
After downloading the archive , extract it to a folder of your choice.
Say .. Downloads
or whatever.. So it will look like Downloads/solr-4.8.1/
On your prompt.. Navigate inside the directory
shankar@shankar-lenovo: cd Downloads/solr-4.8.1
So now you are here ..
shankar@shankar-lenovo: ~/Downloads/solr-4.8.1$
Jetty is available inside the examples folder of the solr-4.8.1
directory , so navigate inside that and start the Jetty Application Server.
shankar@shankar-lenovo:~/Downloads/solr-4.8.1/example$ java -jar start.jar
Now , do not close the terminal , minimize it and let it stay aside.
( TIP : Use & after start.jar to make the Jetty Server run in the background )
To check if Apache Solr runs successfully, visit this URL on the browser. http://localhost:8983/solr
It runs on the port 8983 as default. You could change the port either here or directly inside the jetty.xml
file.
java -Djetty.port=9091 -jar start.jar
This JAR file acts as a bridge between MySQL and JDBC , Download the Platform Independent Version here
After downloading it, extract the folder and copy themysql-connector-java-5.1.31-bin.jar
and paste it to the lib directory.
shankar@shankar-lenovo:~/Downloads/solr-4.8.1/contrib/dataimporthandler/lib
To put Solr to use, You need to have some tables and data to search for. For that, we will use MySQL for creating a table and pushing some random names and then we could use Solr to connect to MySQL and index that table and it's entries.
CREATE TABLE test_solr_mysql
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(45) NULL,
created TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jean');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jack');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jason');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Vego');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Grunt');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jasper');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Fred');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jenna');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Rebecca');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Roland');
shankar@shankar-lenovo: ~/Downloads/solr-4.8.1/example/solr/collection1/conf
Add these two directives to this file..
<lib dir="../../../contrib/dataimporthandler/lib/" regex=".*\.jar" />
<lib dir="../../../dist/" regex="solr-dataimporthandler-\d.*\.jar" />
Now add the DIH (Data Import Handler)
<requestHandler name="/dataimport"
class="org.apache.solr.handler.dataimport.DataImportHandler" >
<lst name="defaults">
<str name="config">db-data-config.xml</str>
</lst>
</requestHandler>
If the file exists then ignore, add these lines to that file. As you can see the first line, you need to provide the credentials of your MySQL database. The Database name, username and password.
<dataConfig>
<dataSource type="JdbcDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/yourdbname" user="dbuser" password="dbpass"/>
<document>
<entity name="test_solr" query="select CONCAT('test_solr-',id) as rid,name from test_solr_mysql WHERE '${dataimporter.request.clean}' != 'false'
OR `created` > '${dataimporter.last_index_time}'" >
<field name="id" column="rid" />
<field name="solr_name" column="name" />
</entity>
</document>
</dataConfig>
( TIP : You can have any number of entities but watch out for id field, if they are same then indexing will skipped. )
Add this to your schema.xml as shown..
<uniqueKey>id</uniqueKey>
<field name="solr_name" type="string" indexed="true" stored="true" />
Implementation
This is where the real deal is. You need to do the indexing of data from MySQL to Solr inorder to make use of Solr Queries.
Hit the URL http://localhost:8983/solr on your browser. The screen opens like this.
As the marker indicates, go to Logging inorder to check if any of the above configuration has led to errors.
Ok so now you are here, As you can there are a lot of yellow messages (WARNINGS). Make sure you don't have error messages marked in red. Earlier, on our configuration we had added a select query on our db-data-config.xml, say if there were any errors on that query, it would have shown up here.
Fine, no errors. We are good to go. Let's choose collection1 from the list as depicted and select Dataimport
Using the DIH, you will be connecting to MySQL from Solr through the configuration file db-data-config.xml from the Solr interface and retrieve the 10 records from the database which gets indexed onto Solr.
To do that, Choose full-import , and check the options Clean and Commit. Now click Execute as shown.
Alternatively, you could use a direct full-import query like this too..
http://localhost:8983/solr/collection1/dataimport?command=full-import&commit=true
After you clicked Execute, Solr begins to index the records, if there were any errors, it would say Indexing Failed and you have to go back to the Logging section to see what has gone wrong.
Assuming there are no errors with this configuration and if the indexing is successfully complete., you would get this notification.
Seems like everything went well, now you could use Solr Queries to query the data that was indexed. Click the Query on the left and then press Execute button on the bottom.
You will see the indexed records as shown.
The corresponding Solr query for listing all the records is
http://localhost:8983/solr/collection1/select?q=*:*&wt=json&indent=true
Well, there goes all 10 indexed records. Say, we need only names starting with Ja , in this case, you need to target the column name solr_name
, Hence your query goes like this.
http://localhost:8983/solr/collection1/select?q=solr_name:Ja*&wt=json&indent=true
That's how you write Solr Queries. To read more about it, Check this beautiful article.
You can include JQuery using any of the following:
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
- http://code.jquery.com/jquery-latest.min.js (never use this link on production server)
Your code placement can look something like this
```
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('input[type=radio]').change(function() {
$('input[type=radio]').each(function(index) {
$(this).closest('tr').removeClass('selected');
});
$(this).closest('tr').addClass('selected');
});
});
</script>
```
That's why it's not working because you code something that is not right, that's why it always exit and the script executer will read it as not operable batch file that prevent it to exit and stop so it must be
tasklist /fi "IMAGENAME eq Notepad.exe" 2>NUL | find /I /N "Notepad.exe">NUL
if "%ERRORLEVEL%"=="0" (
msg * Program is running
goto Exit
)
else if "%ERRORLEVEL%"=="1" (
msg * Program is not running
goto Exit
)
rather than
@echo off
tasklist /fi "imagename eq notepad.exe" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit
something like this? http://codepen.io/Nunotmp/pen/wKjvB
You can add an empty div
and use absolute positioning.
Since Java 5 you can use Arrays.toString(arr)
or Arrays.deepToString(arr)
for arrays within arrays. Note that the Object[]
version calls .toString()
on each object in the array. The output is even decorated in the exact way you're asking.
Examples:
String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));
Output:
[John, Mary, Bob]
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));
Output:
[[John, Mary], [Alice, Bob]]
double
Array:double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(doubleArray));
Output:
[7.0, 9.0, 5.0, 1.0, 3.0 ]
int
Array:int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));
Output:
[7, 9, 5, 1, 3 ]
We can also define it using global
in setupTests
// setupTests.js
global.open = jest.fn()
And call it using global
in the actual test:
// yourtest.test.js
it('correct url is called', () => {
statementService.openStatementsReport(111);
expect(global.open).toBeCalled();
});
From Unix.SE: A simple command-line utility called gpustat
now exists: https://github.com/wookayin/gpustat.
It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi
.
Line break accepts an optional argument in brackets, a vertical length:
line 1
\\[4in]
line 2
To make this more scalable with respect to font size, you can use other lengths, such as \\[3\baselineskip]
, or \\[3ex]
.
You should use this:
<Link to={this.props.myroute} onClick={hello}>Here</Link>
Or (if method hello
lays at this class):
<Link to={this.props.myroute} onClick={this.hello}>Here</Link>
Update: For ES6 and latest if you want to bind some param with click method, you can use this:
const someValue = 'some';
....
<Link to={this.props.myroute} onClick={() => hello(someValue)}>Here</Link>
The following class allows you to copy/paste a String to/from the clipboard.
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import static java.awt.event.KeyEvent.*;
import static org.apache.commons.lang3.SystemUtils.IS_OS_MAC;
public class SystemClipboard
{
public static void copy(String text)
{
Clipboard clipboard = getSystemClipboard();
clipboard.setContents(new StringSelection(text), null);
}
public static void paste() throws AWTException
{
Robot robot = new Robot();
int controlKey = IS_OS_MAC ? VK_META : VK_CONTROL;
robot.keyPress(controlKey);
robot.keyPress(VK_V);
robot.keyRelease(controlKey);
robot.keyRelease(VK_V);
}
public static String get() throws Exception
{
Clipboard systemClipboard = getSystemClipboard();
DataFlavor dataFlavor = DataFlavor.stringFlavor;
if (systemClipboard.isDataFlavorAvailable(dataFlavor))
{
Object text = systemClipboard.getData(dataFlavor);
return (String) text;
}
return null;
}
private static Clipboard getSystemClipboard()
{
Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
return defaultToolkit.getSystemClipboard();
}
}
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
Use saved_change_to_published?
:
class SomeModel < ActiveRecord::Base
after_update :send_notification_after_change
def send_notification_after_change
Notification.send(…) if (saved_change_to_published? && self.published == true)
end
end
Or if you prefer, saved_change_to_attribute?(:published)
.
Warning
This approach works through Rails 5.1 (but is deprecated in 5.1 and has breaking changes in 5.2). You can read about the change in this pull request.
In your after_update
filter on the model you can use _changed?
accessor. So for example:
class SomeModel < ActiveRecord::Base
after_update :send_notification_after_change
def send_notification_after_change
Notification.send(...) if (self.published_changed? && self.published == true)
end
end
It just works.
A variation on some of the answers above but this is how I got the value of a specific tag from the user-data script on an instance
REGION=$(curl http://instance-data/latest/meta-data/placement/availability-zone | sed 's/.$//')
INSTANCE_ID=$(curl -s http://instance-data/latest/meta-data/instance-id)
TAG_VALUE=$(aws ec2 describe-tags --region $REGION --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values='<TAG_NAME_HERE>'" | jq -r '.Tags[].Value')
You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list.
select dbo.fun_functional_score('01091400003')
This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.
There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.
The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like
1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host
EDIT
Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication
Note that there is an unrelated issue in your code but that could bite you later: you should return res.json()
or you will not catch any error occurring in JSON parsing or your own function processing data.
Back to your error: You cannot have a TypeError: failed to fetch
with a successful request. You probably have another request (check your "network" panel to see all of them) that breaks and causes this error to be logged. Also, maybe check "Preserve log" to be sure the panel is not cleared by any indelicate redirection. Sometimes I happen to have a persistent "console" panel, and a cleared "network" panel that leads me to have error in console which is actually unrelated to the visible requests. You should check that.
Or you (but that would be vicious) actually have a hardcoded console.log('TypeError: failed to fetch')
in your final .catch
;) and the error is in reality in your .then()
but it's hard to believe.
You could use the SizeMode property of the PictureBox Control and set it to Center. This will match the center of your image to the center of your picture box.
pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
Hope it could help.
In the command prompt, type the command below and press Enter.
bcdedit /enum
Under the Windows Boot Loader sections, make note of the identifier value.
To start in safe mode from command prompt :
bcdedit /set {identifier} safeboot minimal
Then enter the command line to reboot your computer.
inputString.splitlines()
Will give you a list with each item, the splitlines()
method is designed to split each line into a list element.
The leftmost button (blue cycle) below also reimports all maven projects:
From Wikipedia:
Applications implementing common services often use specifically reserved, well-known port numbers for receiving service requests from client hosts. This process is known as listening and involves the receipt of a request on the well-known port and reestablishing one-to-one server-client communications on another private port, so that other clients may also contact the well-known service port. The well-known ports are defined by convention overseen by the Internet Assigned Numbers Authority (IANA).
So as others mentioned, it's a convention.
Let's fit the model:
> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)
Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)
Residuals:
Min 1Q Median 3Q Max
-245.74 -113.99 -32.05 104.96 484.81
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 811.2267 76.9755 10.539 2.29e-13 ***
body.weight 7.0595 0.9776 7.221 7.03e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433
F-statistic: 52.15 on 1 and 42 DF, p-value: 7.025e-09
The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).
This can be computed using confint
:
> confint(fit, 'body.weight', level=0.95)
2.5 % 97.5 %
body.weight 5.086656 9.0324
It's an old thread, but I'll add some info for other people.
I experienced a similar issue with a program that writes PDF files, sometimes they take 30 seconds to render.. which is the same period that my watcher_FileCreated class waits before copying the file.
The files were not locked.
In this case I checked the size of the PDF and then waited 2 seconds before comparing the new size, if they were unequal the thread would sleep for 30 seconds and try again.
You can use define window.myvar = {}
.
When you want to use it, you can use like window.myvar = 1
Check tis article on Partial Key Verification which covers the following requirements:
License keys must be easy enough to type in.
We must be able to blacklist (revoke) a license key in the case of chargebacks or purchases with stolen credit cards.
No “phoning home” to test keys. Although this practice is becoming more and more prevalent, I still do not appreciate it as a user, so will not ask my users to put up with it.
It should not be possible for a cracker to disassemble our released application and produce a working “keygen” from it. This means that our application will not fully test a key for verification. Only some of the key is to be tested. Further, each release of the application should test a different portion of the key, so that a phony key based on an earlier release will not work on a later release of our software.
Important: it should not be possible for a legitimate user to accidentally type in an invalid key that will appear to work but fail on a future version due to a typographical error.
For the sake of completness, what works best for me is:
git show YOURHASH --no-color -- file1.txt file2.txt dir3 dir4 | git apply -3 --index -
It does exactly what OP wants. It does conflict resolution when needed, similarly how merge
does it. It does add
but not commit
your new changes, see with status
.
Firstly It tries insert. If there is a conflict on url
column then it updates content and last_analyzed fields. If updates are rare this might be better option.
INSERT INTO URLs (url, content, last_analyzed)
VALUES
(
%(url)s,
%(content)s,
NOW()
)
ON CONFLICT (url)
DO
UPDATE
SET content=%(content)s, last_analyzed = NOW();
You have to actively choose to install MSYS to get the make.exe. So you should always have at least (the native) mingw32-make.exe if MinGW was installed properly. And if you installed MSYS you will have make.exe (in the MSYS subfolder probably).
Note that many projects require first creating a makefile (e.g. using a configure script or automake .am file) and it is this step that requires MSYS or cygwin. Makes you wonder why they bothered to distribute the native make at all.
Once you have the makefile, it is unclear if the native executable requires a different path separator than the MSYS make (forward slashes vs backward slashes). Any autogenerated makefile is likely to have unix-style paths, assuming the native make can handle those, the compiled output should be the same.
The implicit make rule for compiling a C program is
%.o:%.c
$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<
where the $()
syntax expands the variables. As both CPPFLAGS
and CFLAGS
are used in the compiler call, which you use to define include paths is a matter of personal taste. For instance if foo.c
is a file in the current directory
make foo.o CPPFLAGS="-I/usr/include"
make foo.o CFLAGS="-I/usr/include"
will both call your compiler in exactly the same way, namely
gcc -I/usr/include -c -o foo.o foo.c
The difference between the two comes into play when you have multiple languages which need the same include path, for instance if you have bar.cpp
then try
make bar.o CPPFLAGS="-I/usr/include"
make bar.o CFLAGS="-I/usr/include"
then the compilations will be
g++ -I/usr/include -c -o bar.o bar.cpp
g++ -c -o bar.o bar.cpp
as the C++ implicit rule also uses the CPPFLAGS
variable.
This difference gives you a good guide for which to use - if you want the flag to be used for all languages put it in CPPFLAGS
, if it's for a specific language put it in CFLAGS
, CXXFLAGS
etc. Examples of the latter type include standard compliance or warning flags - you wouldn't want to pass -std=c99
to your C++ compiler!
You might then end up with something like this in your makefile
CPPFLAGS=-I/usr/include
CFLAGS=-std=c99
CXXFLAGS=-Weffc++
The literal 0
has two meanings in C++.
On the one hand, it is an integer with the value 0.
On the other hand, it is a null-pointer constant.
As your setval
function can accept either an int
or a char*
, the compiler can not decide which overload you meant.
The easiest solution is to just cast the 0
to the right type.
Another option is to ensure the int
overload is preferred, for example by making the other one a template:
class huge
{
private:
unsigned char data[BYTES];
public:
void setval(unsigned int);
template <class T> void setval(const T *); // not implemented
template <> void setval(const char*);
};
Command line usage:
for /f %f in ('dir /b c:\') do echo %f
Batch file usage:
for /f %%f in ('dir /b c:\') do echo %%f
Update: if the directory contains files with space in the names, you need to change the delimiter the for /f
command is using. for example, you can use the pipe char.
for /f "delims=|" %%f in ('dir /b c:\') do echo %%f
Update 2: (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the usebackq
option on the for
:
for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f
And if you need to use output redirection or command piping, use the escape char (^
):
for /f "usebackq delims=|" %%f in (`dir /b "c:\program files" ^| findstr /i microsoft`) do echo %%f
JavaScript code using ng-controller:
$scope.checkkey = function (event) {
alert(event.keyCode); //this will show the ASCII value of the key pressed
}
In HTML:
<input type="text" ng-keypress="checkkey($event)" />
You can now place your checks and other conditions using the keyCode method.
var q = from b in listOfBoxes
group b by b.Owner into g
select new
{
Owner = g.Key,
Boxes = g.Count(),
TotalWeight = g.Sum(item => item.Weight),
TotalVolume = g.Sum(item => item.Volume)
};
You can pass an InputStream to the Property, so your file can pretty much be anywhere, and called anything.
Properties properties = new Properties();
try {
properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
...
}
Iterate as:
for(String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}
Just using an ALTER TABLE should work. Add the column with the proper type and an IDENTITY flag and it should do the trick
Check out this MSDN article http://msdn.microsoft.com/en-us/library/aa275462(SQL.80).aspx on the ALTER TABLE syntax
For me the 'Bla' file was System.Net.http dll which was missing from my BIN folder. I just added it and it worked fine. Didn't change any registry key or anything of that sort.
I think all of the answers here cover the core of what the lambda function does in the context of sorted() quite nicely, however I still feel like a description that leads to an intuitive understanding is lacking, so here is my two cents.
For the sake of completeness, I'll state the obvious up front: sorted() returns a list of sorted elements and if we want to sort in a particular way or if we want to sort a complex list of elements (e.g. nested lists or a list of tuples) we can invoke the key argument.
For me, the intuitive understanding of the key argument, why it has to be callable, and the use of lambda as the (anonymous) callable function to accomplish this comes in two parts.
Lambda syntax is as follows:
lambda input_variable(s): tasty one liner
e.g.
In [1]: f00 = lambda x: x/2
In [2]: f00(10)
Out[2]: 5.0
In [3]: (lambda x: x/2)(10)
Out[3]: 5.0
In [4]: (lambda x, y: x / y)(10, 2)
Out[4]: 5.0
In [5]: (lambda: 'amazing lambda')() # func with no args!
Out[5]: 'amazing lambda'
key
argument is that it should take in a set of instructions that will essentially point the 'sorted()' function at those list elements which should used to sort by. When it says key=
, what it really means is: As I iterate through the list one element at a time (i.e. for e in list), I'm going to pass the current element to the function I provide in the key argument and use that to create a transformed list which will inform me on the order of final sorted list. Check it out:
mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=WhatToSortBy)
Base example:
sorted(mylist)
[2, 3, 3, 4, 6, 8, 23] # all numbers are in order from small to large.
Example 1:
mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=lambda x: x%2==0)
[3, 3, 23, 6, 2, 4, 8] # Does this sorted result make intuitive sense to you?
Notice that my lambda function told sorted to check if (e) was even or odd before sorting.
BUT WAIT! You may (or perhaps should) be wondering two things - first, why are my odds coming before my evens (since my key value seems to be telling my sorted function to prioritize evens by using the mod operator in x%2==0
). Second, why are my evens out of order? 2 comes before 6 right? By analyzing this result, we'll learn something deeper about how the sorted() 'key' argument works, especially in conjunction with the anonymous lambda function.
Firstly, you'll notice that while the odds come before the evens, the evens themselves are not sorted. Why is this?? Lets read the docs:
Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons.
We have to do a little bit of reading between the lines here, but what this tells us is that the sort function is only called once, and if we specify the key argument, then we sort by the value that key function points us to.
So what does the example using a modulo return? A boolean value: True == 1
, False == 0
. So how does sorted deal with this key? It basically transforms the original list to a sequence of 1s and 0s.
[3,6,3,2,4,8,23] becomes [0,1,0,1,1,1,0]
Now we're getting somewhere. What do you get when you sort the transformed list?
[0,0,0,1,1,1,1]
Okay, so now we know why the odds come before the evens. But the next question is: Why does the 6 still come before the 2 in my final list? Well that's easy - its because sorting only happens once! i.e. Those 1s still represent the original list values, which are in their original positions relative to each other. Since sorting only happens once, and we don't call any kind of sort function to order the original even values from low to high, those values remain in their original order relative to one another.
The final question is then this: How do I think conceptually about how the order of my boolean values get transformed back in to the original values when I print out the final sorted list?
Sorted() is a built-in method that (fun fact) uses a hybrid sorting algorithm called Timsort that combines aspects of merge sort and insertion sort. It seems clear to me that when you call it, there is a mechanic that holds these values in memory and bundles them with their boolean identity (mask) determined by (...!) the lambda function. The order is determined by their boolean identity calculated from the lambda function, but keep in mind that these sublists (of one's and zeros) are not themselves sorted by their original values. Hence, the final list, while organized by Odds and Evens, is not sorted by sublist (the evens in this case are out of order). The fact that the odds are ordered is because they were already in order by coincidence in the original list. The takeaway from all this is that when lambda does that transformation, the original order of the sublists are retained.
So how does this all relate back to the original question, and more importantly, our intuition on how we should implement sorted() with its key argument and lambda?
That lambda function can be thought of as a pointer that points to the values we need to sort by, whether its a pointer mapping a value to its boolean transformed by the lambda function, or if its a particular element in a nested list, tuple, dict, etc., again determined by the lambda function.
Lets try and predict what happens when I run the following code.
mylist = [(3, 5, 8), (6, 2, 8), ( 2, 9, 4), (6, 8, 5)]
sorted(mylist, key=lambda x: x[1])
My sorted
call obviously says, "Please sort this list". The key argument makes that a little more specific by saying, for each element (x) in mylist, return index 1 of that element, then sort all of the elements of the original list 'mylist' by the sorted order of the list calculated by the lambda function. Since we have a list of tuples, we can return an indexed element from that tuple. So we get:
[(6, 2, 8), (3, 5, 8), (6, 8, 5), (2, 9, 4)]
Run that code, and you'll find that this is the order. Try indexing a list of integers and you'll find that the code breaks.
This was a long winded explanation, but I hope this helps to 'sort' your intuition on the use of lambda functions as the key argument in sorted() and beyond.
To create a new screen with the name foo
, use
screen -S foo
Then to reattach it, run
screen -r foo # or use -x, as in
screen -x foo # for "Multi display mode" (see the man page)
You can try:
<VirtualHost myvhost:80>
php_value error_log "/var/log/httpd/vhost_php_error_log"
</Virtual Host>
But I'm not sure if it is going to work. I tried on my sites with no success.
Another approach with the Array.ForEach<T> Method (T[], Action<T>)
method of the Array
class
Array.ForEach(myArray, Console.WriteLine);
That takes only one iteration compared to array.ToList().ForEach(Console.WriteLine)
which takes two iterations and creates internally a second array for the List
(double iteration runtime and double memory consumtion)
Using jQuery appendTo try this:
var holdyDiv = $('<div></div>').attr('id', 'holdy');
holdyDiv.appendTo('body');
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
print(color.BOLD + 'Hello World !' + color.END)
It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return
statement. When the code goes down that path, the function ends with no value returned, and so returns None
.
Updated: It sounds like your code looks like this:
def b(self, p, data):
current = p
if current.data == data:
return True
elif current.data == 1:
return False
else:
self.b(current.next, data)
That else clause is your None
path. You need to return the value that the recursive call returns:
else:
return self.b(current.next, data)
BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.
header file lives at
/usr/include/SDL/SDL.h
__OR__
/usr/include/SDL2/SDL.h # for SDL2
in your c++ code pull in this header using
#include <SDL.h>
__OR__
#include <SDL2/SDL.h> // for SDL2
you have the correct usage of
sdl-config --cflags --libs
__OR__
sdl2-config --cflags --libs # sdl2
which will give you
-I/usr/include/SDL -D_GNU_SOURCE=1 -D_REENTRANT
-L/usr/lib/x86_64-linux-gnu -lSDL
__OR__
-I/usr/include/SDL2 -D_REENTRANT
-lSDL2
at times you may also see this usage which works for a standard install
pkg-config --cflags --libs sdl
__OR__
pkg-config --cflags --libs sdl2 # sdl2
which supplies you with
-D_GNU_SOURCE=1 -D_REENTRANT -I/usr/include/SDL -lSDL
__OR__
-D_REENTRANT -I/usr/include/SDL2 -lSDL2 # SDL2
Simplest way is:
bgSound = new Audio("sounds/background.mp3");
bgSound.loop = true;
bgSound.play();
Maven does not easily support non-standard operations. The number of useful plugins is though constantly growing. Neither Maven, nor Ant easily/intrinsically support the file dependency concept of Make.
Please see this link.
I looked in all my apache log files until I found the actual error (I had changed the <VirtualHost>
from _default_
to my fqdn
). When I fixed this error, everything worked fine.
./Database/DataModels/RelationalDataModel/WeakEntity
It probably can be written in two factors:
If we would think of a database holding questions and answers, then the questions would be the strong entity and the answers would be the weak entity. So, Question (id, text) and Answer (number, question_id, text) would be our tables. But why is the Answer's table a weak entity?
Dependence to the question table. Every answer is connected to one question (assumption) and so it cannot be on its own. That is why we have people who ask one question and answer it themselves so that they can help other people and get some extra likings.
Identification from the primary key of the question. One would not be able to identify an answer (assuming that its id is a number identifier) because a question might be answered by answers whose identifier might exist in other questions too. Primary key of the answer table: (number, question_id).
You would do:
char c = str[1];
Or even:
char c = "Hello"[1];
edit: updated to find the "E".
I had same problem. There are two ways to solve this issue.
You can manually clear each FormArray element by calling the removeAt(i)
function in a loop.
clearFormArray = (formArray: FormArray) => {
while (formArray.length !== 0) {
formArray.removeAt(0)
}
}
The advantage to this approach is that any subscriptions on your
formArray
, such as that registered withformArray.valueChanges
, will not be lost.
See the FormArray documentation for more information.
You can replace whole FormArray with a new one.
clearFormArray = (formArray: FormArray) => {
formArray = this.formBuilder.array([]);
}
This approach causes an issue if you're subscribed to the
formArray.valueChanges
observable! If you replace the FromArray with a new array, you will lose the reference to the observable that you're subscribed to.
I had same problem with 'parallax' plugin.
I changed jQuery librery version to *jquery-1.6.4*
from *jquery-1.10.2*.
And error cleared.
Just in case that the remote file needs your credential to get accessed, you can generate a System.Net.WebClient object using cmdlet New-Object to "Copy File Remotely", like so
$Source = "\\192.168.x.x\somefile.txt"
$Dest = "C:\Users\user\somefile.txt"
$Username = "username"
$Password = "password"
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$WebClient.DownloadFile($Source, $Dest)
Or if you need to upload a file, you can use UploadFile:
$Dest = "\\192.168.x.x\somefile.txt"
$Source = "C:\Users\user\somefile.txt"
$WebClient.UploadFile($Dest, $Source)
Here is a quick and easy solution:
CREATE FUNCTION dbo.vaValidEmail(@EMAIL varchar(100))
RETURNS bit as
BEGIN
DECLARE @bitRetVal as Bit
IF (@EMAIL <> '' AND @EMAIL NOT LIKE '_%@__%.__%')
SET @bitRetVal = 0 -- Invalid
ELSE
SET @bitRetVal = 1 -- Valid
RETURN @bitRetVal
END
Then you can find all rows by using the function:
SELECT * FROM users WHERE dbo.vaValidEmail(email) = 0
If you are not happy with creating a function in your database, you can use the LIKE-clause directly in your query:
SELECT * FROM users WHERE email NOT LIKE '_%@__%.__%'
Roughly you can do it like that :
try
{
//do something
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
if (!Page.IsStartupScriptRegistered("myErrorScript"))
{
Page.ClientScript.RegisterStartupScript("myErrorScript", script);
}
}
But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.
As is defined in RFC 1341:
In the Extended BNF notation of RFC 822, a Content-Type header field value is defined as follows:
Content-Type := type "/" subtype *[";" parameter]
type := "application" / "audio" / "image" / "message" / "multipart" / "text" / "video" / x-token
x-token := < The two characters "X-" followed, with no intervening white space, by any token >
subtype := token
parameter := attribute "=" value
attribute := token
value := token / quoted-string
token := 1*
tspecials := "(" / ")" / "<" / ">" / "@" ; Must be in / "," / ";" / ":" / "\" / <"> ; quoted-string, / "/" / "[" / "]" / "?" / "." ; to use within / "=" ; parameter values
And a list of known MIME types that can follow it (or, as Joe remarks, the IANA source).
As you can see the list is way too big for you to validate against all of them. What you can do is validate against the general format and the type
attribute to make sure that is correct (the set of options is small) and just assume that what follows it is correct (and of course catch any exceptions you might encounter when you put it to actual use).
Also note the comment above:
If another primary type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid any potential conflict with a future official name.
You'll notice that a lot of HTTP requests/responses include an X-
header of some sort which are self defined, keep this in mind when validating the types.
env VAR=value myScript args ...
I solved a situation where I needed a template for the element that would handle alternatively a regular URL or a javascript call, where the js function needs a reference to the calling element. In javascript, "this" works as a self reference only in the context of a form element, e.g., a button. I didn't want a button, just the apperance of a regular link.
Examples:
<a onclick="http://blahblah" href="http://blahblah" target="_blank">A regular link</a>
<a onclick="javascript:myFunc($(this));return false" href="javascript:myFunc($(this));" target="_blank">javascript with self reference</a>
The href and onClick attributes have the same values, exept I append "return false" on onClick when it's a javascript call. Having "return false" in the called function did not work.
(('a a a').match(/b/g) || []).length; // 0
(('a a a').match(/a/g) || []).length; // 3
Based on https://stackoverflow.com/a/48195124/16777 but fixed to actually work in zero-results case.
Just adding the #include <math.h>
in c source file and -lm in Makefile at the end will work for me.
gcc -pthread -o p3 p3.c -lm
How about calling the .NET Framework methods?
You can do ANYTHING with them... :
[System.IO.File]::Copy($src, $dest, $true);
The $true
argument makes it overwrite.
In C++ it is done like this:
#define LOCAL_PI 3.1415926535897932385
double ToRadians(double degrees)
{
double radians = degrees * LOCAL_PI / 180;
return radians;
}
double DirectDistance(double lat1, double lng1, double lat2, double lng2)
{
double earthRadius = 3958.75;
double dLat = ToRadians(lat2-lat1);
double dLng = ToRadians(lng2-lng1);
double a = sin(dLat/2) * sin(dLat/2) +
cos(ToRadians(lat1)) * cos(ToRadians(lat2)) *
sin(dLng/2) * sin(dLng/2);
double c = 2 * atan2(sqrt(a), sqrt(1-a));
double dist = earthRadius * c;
double meterConversion = 1609.00;
return dist * meterConversion;
}
Try out cat
and sprintf
in your for loop.
eg.
cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))
See here
I used this, and it worked perfectly.
error: function(xhr, status, error){
alertify.error(JSON.parse(xhr.responseText).error);
}
You only have tried comma-separated and semicolon-separated CSV. If you had tried tab-separated CSV (also called TSV) you would have found the answer:
UTF-16LE with BOM (byte order mark), tab-separated
But: In a comment you mention that TSV is not an option for you (I haven't been able to find this requirement in your question though). That's a pity. It often means that you allow manual editing of TSV files, which probably is not a good idea. Visual checking of TSV files is not a problem. Furthermore editors can be set to display a special character to mark tabs.
And yes, I tried this out on Windows and Mac.
The code presented here doesn't show this discrepancy, but sometimes I get stuck when invoking dataframe
in all lower case.
Switching to camel-case (pd.DataFrame()
) cleans up the problem.
SELECT DeptID, MAX(Salary)
FROM EmpDetails
GROUP BY DeptID
This query will work fine, but the moment if you want to fetch some others details related to the employee having the highest salary will contradict. You can use :
SELECT DepatID, a , b, c
FROM EmpDetails
WHERE Salary IN (
SELECT max(Salary)
FROM EmpDetails
GROUP BY DeptID
);
if you will use the previous query it will only reflects the records of the min val except the salary as you have used the max function.
If you need the construct for a quick example to play with, use the : operator.
But if you are creating a vector/range of numbers dynamically, then use seq() instead.
Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.
In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,
seq(a, b, -1)
will raise an error for a=2, b=6, because the coder expected a decreasing sequence.
I think you could experiment with different activity flags, as it sounds like multiple instances.
"singleTop" "singleTask" "singleInstance"
Are the ones I would try, they can be defined inside the manifest.
http://developer.android.com/guide/topics/manifest/activity-element.html
I got it working with a call to something as simple as
function fb_login() {
FB.login( function() {}, { scope: 'email,public_profile' } );
}
I don't know if facebook will ever be able to block this circumvention, but for now I can use whatever HTML or image I want to call fb_login
and it works fine.
Reference: Facebook API Docs
Another way to solve this is like this:
tensor_shape[0].value
This will return the int value of the Dimension object.
Have you tried setting the selection properties of your tableView like this:
tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES;
If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
in your UITableView delegate. The documentation states:
Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
You can have this method return nil in cases where you don't want the selection to happen.
In my case, the problem was another. I was trying convert lists of lists of int to array. The problem was that there was one list with a different length than others. If you want to prove it, you must do:
print([i for i,x in enumerate(list) if len(x) != 560])
In my case, the length reference was 560.
No.
Sometimes you can quote the filename.
"C:\Program Files\Something"
Some programs will tolerate the quotes. Since you didn't provide any specific program, it's impossible to tell if quotes will work for you.
NULL
is not a built-in constant in the C or C++ languages. In fact, in C++ it's more or less obsolete, just use a plain literal 0
instead, the compiler will do the right thing depending on the context.
In newer C++ (C++11 and higher), use nullptr
(as pointed out in a comment, thanks).
Otherwise, add
#include <stddef.h>
to get the NULL
definition.
<?php
if(isset($_POST['btnSave'])){
$j = 0; //Variable for indexing uploaded image
$file_name_all="";
$target_path = "uploads/"; //Declaring Path for uploaded images
//loop to get individual element from the array
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$basename=basename($_FILES['file']['name'][$i]);
//echo"hi its base name".$basename;
$target_path = $target_path .$basename;//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < (1024*1024)) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
/***********************************************/
$file_name_all.=$target_path."*";
$filepath = rtrim($file_name_all, '*');
//echo"<img src=".$filepath." >";
/*************************************************/
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
$qry="INSERT INTO `eb_re_about_us`(`er_abt_us_id`, `er_cli_id`, `er_cli_abt_info`, `er_cli_abt_img`) VALUES (NULL,'$b1','$b5','$filepath')";
$res = mysql_query($qry,$conn);
if($res)
echo "<br/><br/>Client contact Person Information Details Saved successfully";
//header("location: nextaddclient.php");
//exit();
else
echo "<br/><br/>Client contact Person Information Details not saved successfully";
}
?>
Here $file_name_all And $filepath get 1 uplode file name 2 time?
use HashSet
it's better
take a look here : http://www.dotnetperls.com/hashset
You should use datetime.datetime.strptime
:
import datetime
dt = datetime.datetime.strptime(string_date, fmt)
fmt
will need to be the appropriate format for your string. You'll find the reference on how to build your format here.
In addition to all the other correct answers, since Rails.root
is a Pathname
object, this won't work:
Rails.root + '/app/assets/...'
You could use something like join
Rails.root.join('app', 'assets')
If you want a string use this:
Rails.root.join('app', 'assets').to_s
if you insist on using Bootstrap, use d-inline-block
like below
<div class="row d-inline-block">
<form class="form-inline">
<div class="form-group d-inline-block">
<input type="email" aria-expanded="false" class="form-control mr-2"
placeholder="Enter your email">
<button type="button" class="btn btn-danger">submit</button>
</div>
</form>
</div>
Use this to transform a moment object into a date object:
From http://momentjs.com/docs/#/displaying/as-javascript-date/
moment().toDate();
Yields:
Tue Nov 04 2014 14:04:01 GMT-0600 (CST)
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
int main()
{
vector<int>v1;
for(int i=0; i<5; i++)
v1.push_back(i*2);
for(int i=0; i<v1.size(); i++)
cout<<v1[i]; //02468
reverse(v1.begin(),v1.end());
for(int i=0; i<v1.size(); i++)
cout<<v1[i]; //86420
}
Use insert method from range, for example
Sub InsertColumn()
Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("C1").Value = "Loc"
End Sub
To check if mod_rewrite module is enabled, create a new php file in your root folder of your WAMP server. Enter the following
phpinfo();
Access your created file from your browser.
CtrlF to open a search. Search for 'mod_rewrite'. If it is enabled you see it as 'Loaded Modules'
If not, open httpd.conf (Apache Config file) and look for the following line.
#LoadModule rewrite_module modules/mod_rewrite.so
Remove the pound ('#') sign at the start and save the this file.
Restart your apache server.
Access the same php file in your browser.
Search for 'mod_rewrite' again. You should be able to find it now.
In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before
css to match yours.
In case if it is IE10 then using below css3 it is possible
select::-ms-expand {
display: none;
}
However if you're interested in jQuery plugin, try Chosen.js
or you can create your own in js.
Use the pandas.DataFrame.round() method like this:
df = df.round({'value1': 0})
Any columns not included will be left as is.
You need to use a regular expression, so that you can specify the global (g) flag:
var s = 'some+multi+word+string'.replace(/\+/g, ' ');
(I removed the $()
around the string, as replace
is not a jQuery method, so that won't work at all.)
Replace Null Values as Empty: ISNULL('Value','')
Replace Null Values as 0: ISNULL('Value',0)
There's also split_whitespace()
fn main() {
let words: Vec<&str> = " foo bar\t\nbaz ".split_whitespace().collect();
println!("{:?}", words);
// ["foo", "bar", "baz"]
}
Like Andrew said /exclude
parameter of xcopy should be existing file that has list of excludes.
Documentation of xcopy says:
Using /exclude
List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.
Example:
xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
and list-of-excluded-files.txt
should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:
exclusion.txt
As Omu pointed out, you must set the focus in a document ready function. jQuery provides it for you. And do select on an id. For example, if you have a login page:
$(function() { $("#login-user-name").focus(); }); // jQuery rocks!
Both works fine. But according to the Apache docs you should avoid using mod_rewrite
for simple redirections, and use Redirect
instead. So according to them, you should preferably do:
<VirtualHost *:80>
ServerName www.example.com
Redirect / https://www.example.com/
</VirtualHost>
<VirtualHost *:443>
ServerName www.example.com
# ... SSL configuration goes here
</VirtualHost>
The first /
after Redirect
is the url, the second part is where it should be redirected.
You can also use it to redirect URLs to a subdomain:
Redirect /one/ http://one.example.com/
I had read yesterday that the issue was fixed for someone when that person cleared cookies. I had tried that but it did not work for me.
Checking the following section in DatabaseInterface.class.php,
define(
'PMA_MYSQL_INT_VERSION',
PMA_Util::cacheGet('PMA_MYSQL_INT_VERSION', true)
);
I figured that somehow cache is the problem. So, I remembered that I was restarting the service instead of doing a start
and stop
.
# restart the service
systemd restart php-fpm
# start and stop the service
systemd stop php-fpm
systemd start php-fpm
Doing a stop
followed by a start
fixed the issue for me.
For batch processing with files in folder aiming for 190 VBR and file extension = .mp3 instead of .ac3.mp3 you can use the following code
Change .ac3 to whatever the source audio format is.
for f in *.ac3 ; do ffmpeg -i "$f" -acodec libmp3lame -q:a 2 "${f%.*}.mp3"; done
1.Download and install: Microsoft Office Developer Tools
2.Add references from:
C:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office15
If you want to prevent the user from enter non-numeric values at the time of enter the information in the TextBox, you can use the Event OnKeyPress like this:
private void txtAditionalBatch_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar)) e.Handled = true; //Just Digits
if (e.KeyChar == (char)8) e.Handled = false; //Allow Backspace
if (e.KeyChar == (char)13) btnSearch_Click(sender, e); //Allow Enter
}
This solution doesn't work if the user paste the information in the TextBox using the mouse (right click / paste) in that case you should add an extra validation.
You can call pack_forget
to remove a widget (if you use pack
to add it to the window).
Example:
from tkinter import *
root = Tk()
b = Button(root, text="Delete me", command=lambda: b.pack_forget())
b.pack()
root.mainloop()
If you use pack_forget
, you can later show the widget again calling pack
again. If you want to permanently delete it, call destroy
on the widget (then you won't be able to re-add it).
If you use the grid
method, you can use grid_forget
or grid_remove
to hide the widget.
While this is very likely to be lost at the bottom of so many answers, the top solutions here were not working for me.
As far as I could tell neither would any of the other answers have helped.
Situation:
In an HTML5 page I had a menu that was a nav element inside a header (not THE header but a header in another element).
I wanted the navigation to stick to the top once a user scrolled to it, but previous to this the header was absolute positioned (so I could have it overlay something else slightly).
The solutions above never triggered a change because .offsetTop was not going to change as this was an absolute positioned element. Additionally the .scrollTop property was simply the top of the top most element... that is to say 0 and always would be 0.
Any tests I performed utilizing these two (and same with getBoundingClientRect results) would not tell me if the top of the navigation bar ever scrolled to the top of the viewable page (again, as reported in console, they simply stayed the same numbers while scrolling occurred).
Solution
The solution for me was utilizing
window.visualViewport.pageTop
The value of the pageTop property reflects the viewable section of the screen, therefore allowing me to track where an element is in reference to the boundaries of the viewable area.
Probably unnecessary to say, anytime I am dealing with scrolling I expect to use this solution to programatically respond to movement of elements being scrolled.
Hope it helps someone else.
IMPORTANT NOTE: This appears to work in Chrome and Opera currently & definitely not in Firefox (6-2018)... until Firefox supports visualViewport I recommend NOT using this method, (and I hope they do soon... it makes a lot more sense than the rest).
UPDATE:
Just a note regarding this solution.
While I still find what I discovered to be very valuable for situations in which "...programmatically respond to movement of elements being scrolled." is applicable. The better solution for the problem that I had was to use CSS to set position: sticky on the element. Using sticky you can have an element stay at the top without using javascript (NOTE: there are times this will not work as effectively as changing the element to fixed but for most uses the sticky approach will likely be superior)
UPDATE01:
So I realized that for a different page I had a requirement where I needed to detect the position of an element in a mildly complex scrolling setup (parallax plus elements that scroll past as part of a message).
I realized in that scenario that the following provided the value I utilized to determine when to do something:
let bodyElement = document.getElementsByTagName('body')[0];
let elementToTrack = bodyElement.querySelector('.trackme');
trackedObjPos = elementToTrack.getBoundingClientRect().top;
if(trackedObjPos > 264)
{
bodyElement.style.cssText = '';
}
Hope this answer is more widely useful now.
try this
!pip install opencv-contrib-python==4.4.0.44 sift = cv2.SIFT_create()
Make sure Anonymous access is enabled on IIS -> Authentication.
But also right click on it, then click on Edit, and choose a domain\username and password. (With access to the physical folder of the application).
If you're setting the button text by using the 'value' attribute you'll need to set
instead of:
Also in my situation it worked better to add the JQuery direct to the onclick event of the button:
onclick="$(this).val(function (i, text) { return text == 'PUSH ME' ? 'DON'T PUSH ME' : 'PUSH ME'; });"
1-Install AjaxControl Toolkit easily by Nugget
PM> Install-Package AjaxControlToolkit
2-then in markup
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:TextBox ID="txtMovie" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" TargetControlID="txtMovie"
runat="server" />
3- in code-behind : to get the suggestions
[System.Web.Services.WebMethodAttribute(),System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey) {
// Create array of movies
string[] movies = {"Star Wars", "Star Trek", "Superman", "Memento", "Shrek", "Shrek II"};
// Return matching movies
return (from m in movies where m.StartsWith(prefixText,StringComparison.CurrentCultureIgnoreCase) select m).Take(count).ToArray();
}
source: http://www.asp.net/ajaxlibrary/act_autocomplete_simple.ashx
In android NDK go to android-ndk-r9b>/sources/cxx-stl/gnu-libstdc++/4.X/include in linux machines
I've found solution from the below link http://osdir.com/ml/android-ndk/2011-09/msg00336.html
Your meta tag should look like this:
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
And it has to be placed on the page you want to share (this is unclear in your question).
If you have shared the page before the image (or the meta tag) was present, then it is possible, that facebook has the page in its "memory" without an image. In this case simply enter the URL of your page in the debug tool http://developers.facebook.com/tools/debug. After that, the image should be present when the page is shared the next time.
sp_spaceused
Simply modern answer is because the tag is denoted as mandatory that way
Tag omission None, both the starting and ending tag are mandatory.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
Found it on another thread that solved my problem... was using an internet connection less network.
In that case copy the xsd files from the url and place it next to the beans.xml file and change the xsi:schemaLocation as under:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
spring-beans-3.1.xsd">
Check Demo: https://stackblitz.com/edit/angular-6-checkbox?embed=1&file=src/app/app.component.html
CheckBox: use change event to call the function and pass the event.
<label class="container">
<input type="checkbox" [(ngModel)]="theCheckbox" data-md-icheck
(change)="toggleVisibility($event)"/>
Checkbox is <span *ngIf="marked">checked</span><span
*ngIf="!marked">unchecked</span>
<span class="checkmark"></span>
</label>
<div>And <b>ngModel</b> also works, it's value is <b>{{theCheckbox}}</b></div>
Please use count function, Here is a example how to count array in a element
$cars = array("Volvo","BMW","Toyota");
echo count($cars);
The count()
function returns the number of elements in an array.
The sizeof()
function returns the number of elements in an array.
The sizeof()
function is an alias of the count()
function.
The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql
No, just use the value directly:
begin
if (select count(*) from table) > 0 then
update table
end if;
end;
Note there is no need for an "else".
You can simply do it all within the update statement (ie no if
construct):
update table
set ...
where ...
and exists (select 'x' from table where ...)
If you are using any Payment Gateway to hit any url just to send a message, then i used a webview by following it : How can load https url without use of ssl in android webview
and make a webview in your activity with visibility gone. What you need to do : just load that webview.. like this:
webViewForSms.setWebViewClient(new SSLTolerentWebViewClient());
webViewForSms.loadUrl(" https://bulksms.com/" +
"?username=test&password=test@123&messageType=text&mobile="+
mobileEditText.getText().toString()+"&senderId=ATZEHC&message=Your%20OTP%20for%20A2Z%20registration%20is%20124");
Easy.
You will get this: SSLTolerentWebViewClient from this link: How can load https url without use of ssl in android webview
1) Run the command java -jar lombok-1.16.10.jar
. This needs to be run from the directory of your lombok.jar file.
2) Add the location manually by selecting the eclipse.ini file(Installed eclipse directory). Through “Specify location”
Note : Don't add the eclipse.exe because it will make the eclipse editor corrupt.
Java code for start service:
Start service from Activity:
startService(new Intent(MyActivity.this, MyService.class));
Start service from Fragment:
getActivity().startService(new Intent(getActivity(), MyService.class));
MyService.java:
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
private static String TAG = "MyService";
private Handler handler;
private Runnable runnable;
private final int runTime = 5000;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate");
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
handler.postDelayed(runnable, runTime);
}
};
handler.post(runnable);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
if (handler != null) {
handler.removeCallbacks(runnable);
}
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.i(TAG, "onStart");
}
}
Define this Service into Project's Manifest File:
Add below tag in Manifest file:
<service android:enabled="true" android:name="com.my.packagename.MyService" />
Done
Use:
AND oh.tran_date BETWEEN TRUNC(SYSDATE - 1) AND TRUNC(SYSDATE) - 1/86400
Reference: TRUNC
Calling a function on the tran_date
means the optimizer won't be able to use an index (assuming one exists) associated with it. Some databases, such as Oracle, support function based indexes which allow for performing functions on the data to minimize impact in such situations, but IME DBAs won't allow these. And I agree - they aren't really necessary in this instance.
For XHTML files: Web -> HTML Files -> Editor -> Line width
sudo
is a Unix/Linux command. It's not available in Windows.
public void Method()
{
if(something)
{
//some code
if(something2)
{
// The code i want to go if the second if is true
}
return;
}
}
One way should be to add a <div style="min-width:XXXpx">
within the td, and let the <td style="width:100%">
Basing on Ilya's data, I wrote a Vanilla JS library for supporting modifier keys on Mac: https://github.com/MichaelZelensky/jsLibraries/blob/master/macKeys.js
Just use it like this, e.g.:
document.onclick = function (event) {
if (event.shiftKey || macKeys.shiftKey) {
//do something interesting
}
}
Tested on Chrome, Safari, Firefox, Opera on Mac. Please check if it works for you.
String#toLowerCase and String#toUpperCase are the methods you need.
I did a log file which prints data into text file using "Winston" log. The source code is here below,
const { createLogger, format, transports } = require('winston');
var fs = require('fs')
var logger = fs.createWriteStream('Data Log.txt', {`
flags: 'a'
})
const os = require('os');
var sleep = require('system-sleep');
var endOfLine = require('os').EOL;
var t = ' ';var s = ' ';var q = ' ';
var array1=[];
var array2=[];
var array3=[];
var array4=[];
array1[0] = 78;`
array1[1] = 56;
array1[2] = 24;
array1[3] = 34;
for (var n=0;n<4;n++)
{
array2[n]=array1[n].toString();
}
for (var k=0;k<4;k++)
{
array3[k]=Buffer.from(' ');
}
for (var a=0;a<4;a++)
{
array4[a]=Buffer.from(array2[a]);
}
for (m=0;m<4;m++)
{
array4[m].copy(array3[m],0);
}
logger.write('Date'+q);
logger.write('Time'+(q+' '))
logger.write('Data 01'+t);
logger.write('Data 02'+t);
logger.write('Data 03'+t);
logger.write('Data 04'+t)
logger.write(endOfLine);
logger.write(endOfLine);
enter code here`enter code here`
}
function mydata() //user defined function
{
logger.write(datechar+s);
logger.write(timechar+s);
for ( n = 0; n < 4; n++)
{
logger.write(array3[n]);
}
logger.write(endOfLine);
}
for (;;)
}
var now = new Date();
var dateFormat = require('dateformat');
var date = dateFormat(now,"isoDate");
var time = dateFormat(now, "h:MM:ss TT ");
var datechar = date.toString();
var timechar = time.toString();
mydata();
sleep(5*1000);
}
Try (untested):
$.getJSON("data.php", function(data){
$.each(data.justIn, function() {
$.each(this, function(k, v) {
alert(k + ' ' + v);
});
});
$.each(data.recent, function() {
$.each(this, function(k, v) {
alert(k + ' ' + v);
});
});
$.each(data.old, function() {
$.each(this, function(k, v) {
alert(k + ' ' + v);
});
});
});
I figured, three separate loops since you'll probably want to treat each dataset differently (justIn, recent, old). If not, you can do:
$.getJSON("data.php", function(data){
$.each(data, function(k, v) {
alert(k + ' ' + v);
$.each(v, function(k1, v1) {
alert(k1 + ' ' + v1);
});
});
});
One other really good reason to use a bitmask vs individual bools is as a web developer, when integrating one website to another, we frequently need to send parameters or flags in the querystring. As long as all of your flags are binary, it makes it much simpler to use a single value as a bitmask than send multiple values as bools. I know there are otherways to send data (GET, POST, etc.), but a simple parameter on the querystring is most of the time sufficient for nonsensitive items. Try to send 128 bool values on a querystring to communicate with an external site. This also gives the added ability of not pushing the limit on url querystrings in browsers
What you assign one object to another, all you're doing is copying the reference to the object, not the contents of it. What you need to do is take your object B and manually copy the contents of object A into it.
If you do this often, you might consider implementing a clone()
method on the class that will create a new object of the same type, and copy all of it's contents into the new object.
Not the same, but idea that works anyway.
#!/bin/bash
i='y'
while [ ${i:0:1} != n ]
do
# Command(s)
read -p " Again? Y/n " i
[[ ${#i} -eq 0 ]] && i='y'
done
Output:
Again? Y/n N
Again? Y/n Anything
Again? Y/n 7
Again? Y/n &
Again? Y/n nsijf
$
Now only checks 1st character of $i read.
I've been in this (Twitter) industry for a long time and witnessed lots of changes in Twitter API and documentation. I would like to clarify one thing to you. There is no way to surpass 3200 tweets limit. Twitter doesn't provide this data even in its new premium API.
The only way someone can surpass this limit is by saving the tweets of an individual Twitter user.
There are tools available which claim to have a wide database and provide more than 3200 tweets. Few of them are followersanalysis.com, keyhole.co which I know of.