Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
Your model is @Messages
, change it to @message
.
To change it like you should use migration:
def change rename_table :old_table_name, :new_table_name end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db
dir. Then run:
rake db:migrate
And your app should be fine since then.
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.
Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.
To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
Look at java.lang.BigDecimal, may solve your problem.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.
Here an example:
print ('This is \x1b[31mred\x1b[0m.')
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
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 your controller, render the new
action from your create action if validation fails, with an instance variable, @car
populated from the user input (i.e., the params
hash). Then, in your view, add a logic check (either an if block around the form
or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params
values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car
is set.
I am now using Xcode 11.6, macOS 10.15.6, and iOS 13.5.1.
First the problem was that I was on Xcode 11.4. But I couldn't upgrade since I wasn't on macOS v10.15 (Catalina) yet. (And I couldn't upgrade because my RAID went down and I couldn't make a backup, but that's another saga.)
After upgrading to Catalina, then to Xcode 11.6 I still couldn't build to the device. So I opened Devices and Simulators and unpaired the phone, as mentioned in the comments here. Then when I tried to re-pair, a warning message said that the device was busy (it was not). Finally, after rebooting the phone (had to untether it for it to come back on), cleaning Xcode, and re-pairing the phone, I finally, finally built to the device. So good luck!
For me I was working under Ubuntu
The error disappeared if I use sudo with ng
sudo ng build
sudo ng serve
Working on android studio: 3.6.3 and gradle version:
classpath 'com.android.tools.build:gradle:3.6.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72"
Adding this line in
gradle.properties file
org.gradle.jvmargs=-Xmx512m
Well this is working for me -
run the following code in the console and it will prevent you from disconnecting. Ctrl+ Shift + i to open inspector view . Then go to console.
function ClickConnect(){
console.log("Working");
document.querySelector("colab-toolbar-button#connect").click()
}
setInterval(ClickConnect,60000)
This is due to the way Windows App Execution Aliases work in Git-Bash.
It is a known issue in MSYS2 failing to access Windows reparse points with IO_REPARSE_TAG_APPEXECLINK
As a workaround, you can alias to a function invocation that uses cmd.exe
under the hood.
Add the following to your ~/.bashrc
file::
function python { cmd.exe /c "python $1 $2 $3";}
For python, I'd recommend just toggling off app execution aliases as in the accepted answer, but for libraries that are distributed exclusively through the windows store like winget
, this is your best option.
Instead of converting the class to a function, an easy step would be to create a function to include the jsx for the component which uses the 'classes', in your case the <container></container>
and then call this function inside the return of the class render() as a tag. This way you are moving out the hook to a function from the class. It worked perfectly for me. In my case it was a <table>
which i moved to a function- TableStmt outside and called this function inside the render as <TableStmt/>
In SnackbarContentWrapper
you need to change
<IconButton
key="close"
aria-label="Close"
color="inherit"
className={classes.close}
onClick={onClose}
>
to
<IconButton
key="close"
aria-label="Close"
color="inherit"
className={classes.close}
onClick={() => onClose}
>
so that it only fires the action when you click.
Instead, you could just curry the handleClose
in SingInContainer
to
const handleClose = () => (reason) => {
if (reason === 'clickaway') {
return;
}
setSnackBarState(false)
};
It's the same.
With the release of TypeScript 3.7, optional chaining (the ?
operator) is now officially available.
As such, you can simplify your expression to the following:
const data = change?.after?.data();
You may read more about it from that version's release notes, which cover other interesting features released on that version.
Run the following to install the latest stable release of TypeScript.
npm install typescript
That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null
or undefined
values
const data = change?.after?.data() ?? someOtherData();
After declaring correctly in pubspec.yaml, consider giving full path of the image ex.
'assets/images/about_us.png'
instead of just images/..
worked for me after wasting 2 hours on such a trivial error.
First install your targeted version
npm i [email protected] --save-dev --save-exact
Then before compiling do
npm i
Works in Ubuntu 20.04
Add this line inside <policymap>
<policy domain="module" rights="read|write" pattern="{PS,PDF,XPS}" />
Comment these lines:
<!--
<policy domain="coder" rights="none" pattern="PS" />
<policy domain="coder" rights="none" pattern="PS2" />
<policy domain="coder" rights="none" pattern="PS3" />
<policy domain="coder" rights="none" pattern="EPS" />
<policy domain="coder" rights="none" pattern="PDF" />
<policy domain="coder" rights="none" pattern="XPS" />
-->
For me, none of the solutions work. I had to download the XCode from the App store. It's too big around 12 GB. After installing it works like a charm.
If the error says it can't find Info.plist and it's looking in the wrong path, do the following:
if (this.router && this.router.url === '/') { or your current page url e.g '/home'
window.location.reload();
} else {
this.router.navigate([url]);
}
The reason for this error occurs is that you are using the CryptoListPresenter _presenter
without initializing.
I found that CryptoListPresenter _presenter
would have to be initialized to fix because _presenter.loadCurrencies()
is passing through a null variable at the time of instantiation;
there are two ways to initialize
Can be initialized during an declaration, like this
CryptoListPresenter _presenter = CryptoListPresenter();
In the second, initializing(with assigning some value) it when initState
is called, which the framework will call this method once for each state object.
@override
void initState() {
_presenter = CryptoListPresenter(...);
}
you can use localStorage for storing the json data:
the example is given below:-
let JSONDatas = [
{"id": "Open"},
{"id": "OpenNew", "label": "Open New"},
{"id": "ZoomIn", "label": "Zoom In"},
{"id": "ZoomOut", "label": "Zoom Out"},
{"id": "Find", "label": "Find..."},
{"id": "FindAgain", "label": "Find Again"},
{"id": "Copy"},
{"id": "CopyAgain", "label": "Copy Again"},
{"id": "CopySVG", "label": "Copy SVG"},
{"id": "ViewSVG", "label": "View SVG"}
]
localStorage.setItem("datas", JSON.stringify(JSONDatas));
let data = JSON.parse(localStorage.getItem("datas"));
console.log(data);
What fixed it for me was plugging my iPhone and allowing it as a simulator destination. Doing so required my to register my iPhone in Apple Dev account and once that was done and I ran my project from Xcode on my iPhone everything fixed itself.
If you are stuck after following each of the steps outlined in above, I will suggest you combine more than one answers. The answers of @Kuya and @??? worked for me. Try them out. I can explain more if the steps are yielding results for you.
Try this
products.sort(function (a, b) {
return a.title.rendered - b.title.rendered;
});
OR
You can import lodash/underscore library, it has many build functions available for manipulating, filtering, sorting the array and all.
Using underscore: (below one is just an example)
import * as _ from 'underscore';
let sortedArray = _.sortBy(array, 'title');
As @idleberg mentions, on Mac OS, it is best to install rbenv to avoid permissions errors when using manually installed ruby.
$ brew update
$ brew install rbenv
Add the following in .bashrc
file:
eval "$(rbenv init -)"
Now, we can look at the list of ruby versions available for install
$ rbenv install -l
Install version 2.3.8 for example
$ rbenv install 2.3.8
Now we can use this ruby version globally
$ rbenv global 2.3.8
Finally run
$ rbenv rehash
$ which ruby
/Users/myuser/.rbenv/shims/ruby
$ ruby -v
ruby 2.3.7p456 (2018-03-28 revision 63024) [x86_64-darwin17]
Now install bundler
$ gem install bundler
All done!
Remove this line from your code:
console.info(JSON.parse(scatterSeries));
Google play finds you as developer via your keystore.
and maybe your country IP is banned on Google when you generate your new keystore.
change your IP Address and generate new keystore, the problem will be fixed.
if you didn't succeed, use another Gmail in Android Studio and generate new keystore.
axios.delete is passed a url and an optional configuration.
axios.delete(url[, config])
The fields available to the configuration can include the headers.
This makes it so that the API call can be written as:
const headers = {
'Authorization': 'Bearer paperboy'
}
const data = {
foo: 'bar'
}
axios.delete('https://foo.svc/resource', {headers, data})
* Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080' ^^^^^
The https://
is wrong, it should be http://
. The proxy itself should be accessed by HTTP and not HTTPS even though the target URL is HTTPS. The proxy will nevertheless properly handle HTTPS connection and keep the end-to-end encryption. See HTTP CONNECT method for details how this is done.
You can also customize the card theme globally with ThemeData.cardTheme
:
MaterialApp(
title: 'savvy',
theme: ThemeData(
cardTheme: CardTheme(
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(
Radius.circular(8.0),
),
),
),
// ...
A very simple way to do this is by the following:
onClick={this.fun.bind(this)}
and for the function:
fun() {
this.props.history.push("/Home");
}
finlay you need to import withRouter:
import { withRouter } from 'react-router-dom';
and export it as:
export default withRouter (comp_name);
The Dart language has aspects of functional programming, so what you want can be written concisely as:
List<String> list = ['one', 'two', 'three', 'four'];
List<Widget> widgets = list.map((name) => new Text(name)).toList();
Read this as "take each name
in list
and map it to a Text
and form them back into a List
".
Give connection URL as jdbc:mysql://localhost:3306/hb_student_tracker?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC
This issue is based on your installed version of visual studio and Windows, you can follow the following steps:-
downgraded your PCL by the following command
Install-Package Xamarin.Forms -Version 2.5.1.527436
Upgrade pip as follows:
curl https://bootstrap.pypa.io/get-pip.py | python
Note: You may need to use sudo python
above if not in a virtual environment.
Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.
(Note that upgrading pip via pip install --upgrade pip
will also not upgrade it correctly. It is a chicken-and-egg issue)
This thread explains it (thanks to this Twitter post):
Mac users who use pip and PyPI:
If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:
curl https://bootstrap.pypa.io/get-pip.py | python
and we recommend you do that by April 8th.
Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/
Also, the Python status page:
Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC
Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC
Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:
pip install --upgrade setuptools
Try this
<input class="txt" type="password" [(ngModel)]="input_pw" [hidden]="isHidden">
You can use:
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
To get height just of SafeArea (for iOS 11 and above):
var padding = MediaQuery.of(context).padding;
double newheight = height - padding.top - padding.bottom;
Setting
onPressed: null // disables click
and
onPressed: () => yourFunction() // enables click
There are basically 3 alternatives to cleaning everything that you could try:
flutter clean
will delete the /build
folder./build
folder, which is essentially the same as flutter clean
.place the value inside the items.then it will work,
new DropdownButton<String>(
items:_dropitems.map((String val){
return DropdownMenuItem<String>(
value: val,
child: new Text(val),
);
}).toList(),
hint:Text(_SelectdType),
onChanged:(String val){
_SelectdType= val;
setState(() {});
})
I also read the Spring docs, as lapkritinis suggested - and luckily this brought me on the right path! But I don´t think, that the Spring docs explain this good right now. At least for me, they aren´t consistent IMHO.
The original problem/question is on what to do, if you upgrade an existing Spring Boot 1.5.x application to 2.0.x, which is using PostgreSQL/Hibernate. The main reason, you get your described error, is that Spring Boot 2.0.x uses HikariCP instead of Tomcat JDBC pooling DataSource as a default - and Hikari´s DataSource doesn´t know the spring.datasource.url
property, instead it want´s to have spring.datasource.jdbc-url
(lapkritinis also pointed that out).
So far so good. BUT the docs also suggest - and that´s the problem here - that Spring Boot uses spring.datasource.url
to determine, if the - often locally used - embedded Database like H2 has to back off and instead use a production Database:
You should at least specify the URL by setting the spring.datasource.url property. Otherwise, Spring Boot tries to auto-configure an embedded database.
You may see the dilemma. If you want to have your embedded DataBase like you´re used to, you have to switch back to Tomcat JDBC. This is also much more minimally invasive to existing applications, as you don´t have to change source code! To get your existing application working after the Spring Boot 1.5.x --> 2.0.x upgrade with PostgreSQL, just add tomcat-jdbc
as a dependency to your pom.xml:
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
And then configure Spring Boot to use it accordingly inside application.properties:
spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
Hope to help some folks with this, was quite a time consuming problem. I also hope my beloved Spring folks update the docs - and the way new Hikari pool is configured - to get a more consistent Spring Boot user experience :)
You must use a .ts
file - e.g. test.ts
to get Typescript validation, intellisense typing
of vars, return types, as well as "typed" error checking (e.g. passing a string
to a method that expects an number
param will error out).
It will be transpiled into (standard) .js
via tsc
.
Clarification needed based on down-votes, very helpful comments and other answers.
types
Yes, you can do type
checking in VS Code in .js
files with @ts-check
- as shown in the animation
What I originally was referring to for Typescript types
is something like this in .ts
which isn't quite the same thing:
hello-world.ts
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
This will not compile. Error: Type "1" is not assignable to String
if you tried this syntax in a Javascript hello-world.js
file:
//@ts-check
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file
If there's something I missed that covers this as well as the OP's context, please add. Let's all learn.
I just managed to make it work again. It makes not much sense but it worked:
I'll investigate further later but the method I called with hangfire receives a DBContext and that is the possible cause.
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
Just as Daniel said "Git and TFVC are the two source control options in TFS
". Fortunately both are supported for now in VS Code.
You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.
Add the following lines to your user settings
If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe", "tfvc.restrictWorkspace": true }
Or for VS 2017:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe", "tfvc.restrictWorkspace": true }
Open a local folder (repository), From View -> Command Pallette ..., type team signin
Provide user name --> Enter --> Provide password to connect to TFS.
Please refer to below links for more details:
Note that Server Workspaces are not supported:
"TFVC support is limited to Local workspaces":
The latest set of guidance is as follows: (from https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables)
Use:
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
From the docs:
public static class EnvironmentVariablesExample
{
[FunctionName("GetEnvironmentVariables")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
}
public static string GetEnvironmentVariable(string name)
{
return name + ": " +
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}
}
App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the
Values
collection in the local.settings.json file. In both environments, local and Azure,GetEnvironmentVariable("<app setting name>")
retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains{ "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }
.The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use
GetEnvironmentVariable
as shown here.
Putting my two cents here. I wanted to do the same without hardcoding the URL for my specific request. So i came up with this solution.
To append 'api'
to my baseURL, I have my default baseURL set as,
axios.defaults.baseURL = '/api/';
Then in my specific request, after explicitly setting the method and url, i set the baseURL to '/'
axios({
method:'post',
url:'logout',
baseURL: '/',
})
.then(response => {
window.location.reload();
})
.catch(error => {
console.log(error);
});
Yes there is a way to do it.
First declare a class.
//anyfile.ts
export class Custom
{
name: string,
empoloyeeID: number
}
Then in your component import the class
import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
name: string;
empoloyeeID : number;
empList: Array<Custom> = [];
constructor() {
}
ngOnInit() {
}
onEmpCreate(){
//console.log(this.name,this.empoloyeeID);
let customObj = new Custom();
customObj.name = "something";
customObj.employeeId = 12;
this.empList.push(customObj);
this.name ="";
this.empoloyeeID = 0;
}
}
Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html
Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2
Please double check that jenkins is not blocking this import. Go to script approvals and check to see if it is blocking it. If it is click allow.
I downgraded ruby from 2.5.x to 2.4.x in my particular case.
Quick and easy import from Dropbox:
!pip install dropbox
import dropbox
access_token = 'YOUR_ACCESS_TOKEN_HERE' # https://www.dropbox.com/developers/apps
dbx = dropbox.Dropbox(access_token)
# response = dbx.files_list_folder("")
metadata, res = dbx.files_download('/dataframe.pickle2')
with open('dataframe.pickle2', "wb") as f:
f.write(res.content)
System.setProperty("webdriver.chrome.driver",
"D:\\Lib\\chrome_driver_latest\\chromedriver_win32\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--allow-running-insecure-content");
chromeOptions.addArguments("--window-size=1920x1080");
chromeOptions.addArguments("--disable-gpu");
chromeOptions.setHeadless(true);
ChromeDriver driver = new ChromeDriver(chromeOptions);
Use the below command to solve your issue,
pip install mysql-python
apt-get install python3-mysqldb libmysqlclient-dev python-dev
Works on Debian
new ES6:
'import' should be used with 'export' key words to share variables/arrays/objects between js files:
export default myObject;
//....in another file
import myObject from './otherFile.js';
old skool:
'require' should be used with 'module.exports'
module.exports = myObject;
//....in another file
var myObject = require('./otherFile.js');
By default, package-lock.json
is updated whenever you run npm install
. However, this can be disabled globally by setting package-lock=false
in ~/.npmrc
.
When the global package-lock=false
setting is active, you can still force a project’s package-lock.json
file to be updated by running:
npm install --package-lock
This command is the only surefire way of forcing a package-lock.json
update.
Since none of the above solve my issue, I will post my solution
WARNING: if you just installed TensorFlow using conda, you have to restart your command prompt!
Solution: restart terminal ENTIRELY and restart conda environment
This uses counting to create numeric unique ID. In my use, I will not be decrementing ever, even when the document
that the ID is needed for is deleted.
Upon a collection
creation that needs unique numeric value
appData
with one document, set
with .doc
id only
uniqueNumericIDAmount
to 0 in the firebase firestore console
doc.data().uniqueNumericIDAmount + 1
as the unique numeric idappData
collection uniqueNumericIDAmount
with firebase.firestore.FieldValue.increment(1)
firebase
.firestore()
.collection("appData")
.doc("only")
.get()
.then(doc => {
var foo = doc.data();
foo.id = doc.id;
// your collection that needs a unique ID
firebase
.firestore()
.collection("uniqueNumericIDs")
.doc(user.uid)// user id in my case
.set({// I use this in login, so this document doesn't
// exist yet, otherwise use update instead of set
phone: this.state.phone,// whatever else you need
uniqueNumericID: foo.uniqueNumericIDAmount + 1
})
.then(() => {
// upon success of new ID, increment uniqueNumericIDAmount
firebase
.firestore()
.collection("appData")
.doc("only")
.update({
uniqueNumericIDAmount: firebase.firestore.FieldValue.increment(
1
)
})
.catch(err => {
console.log(err);
});
})
.catch(err => {
console.log(err);
});
});
Please ensure that your mongo DB is set Automatic and running at Control Panel/Administrative Tools/Services like below. That way you wont have to start mongod.exe manually each time.
Just replace @latest
with the version number you want to downgrade to. I wanted to downgrade to version 3.10.10, so I used this command:
npm install -g [email protected]
If you're not sure which version you should use, look at the version history. For example, you can see that 3.10.10 is the latest version of npm 3.
v-flex does not have a display flex! Inspect v-flex in your browser and you will find out it is just a simple block div.
So, you should override it with display: flex
in your HTML or CSS to make it work with justify-content.
When you plug a New device which is having iOS 11, Xcode 9 will Prepare Debugger Support for that device, At this time you should Wait to complete it.
Then run the project in that device it will run smoothly.
If you didn't keep patience while creating Debugger Support then it will throw the error mentioned in the question.
Note for Chrome Browser released in 2020.
A future release of Chrome will only deliver cookies with cross-site requests if they are set with
SameSite=None
andSecure
.
So if your backend server does not set SameSite=None, Chrome will use SameSite=Lax by default and will not use this cookie with { withCredentials: true } requests.
More info https://www.chromium.org/updates/same-site.
Firefox and Edge developers also want to release this feature in the future.
Spec found here: https://tools.ietf.org/html/draft-west-cookie-incrementalism-01#page-8
All of these answers based on dimensions are susceptible to incorrect behavior on future devices. They'll work today, but what if there's an iPhone next year that's the same size but has the camera, etc. under the glass so there's no "notch?" If the only option is to update the app, then it's a poor solution for you and your customers.
You can also check the hardware model string like "iPhone10,1", but that's problematic because sometimes Apple releases different model numbers for different carriers around the world.
The correct approach is to redesign the top layout, or solve the problems you're having with the custom navigation bar height (that's what I'd focus on). But, if you decide not to do either of those things, realize that whatever you're doing is a hack to get this to work today, and you'll need to correct it at some point, perhaps multiple times, to keep the hacks working.
You can use the following below with document.title = 'Home Page'
import React from 'react'
import { Component } from 'react-dom'
class App extends Component{
componentDidMount(){
document.title = "Home Page"
}
render(){
return(
<p> Title is now equal to Home Page </p>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
or You can use this npm package npm i react-document-title
import React from 'react'
import { Component } from 'react-dom'
import DocumentTitle from 'react-document-title';
class App extends Component{
render(){
return(
<DocumentTitle title='Home'>
<h1>Home, sweet home.</h1>
</DocumentTitle>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
Happy Coding!!!
I had a similar issue and solved after running these instructions!
npm install npm -g
npm install --save-dev @angular/cli@latest
npm install
npm start
UPDATE: for rxjs > v5.5
As mentioned in some of the comments and other answers, by default the HttpClient deserializes the content of a response into an object. Some of its methods allow passing a generic type argument in order to duck-type the result. Thats why there is no json()
method anymore.
import {throwError} from 'rxjs';
import {catchError, map} from 'rxjs/operators';
export interface Order {
// Properties
}
interface ResponseOrders {
results: Order[];
}
@Injectable()
export class FooService {
ctor(private http: HttpClient){}
fetch(startIndex: number, limit: number): Observable<Order[]> {
let params = new HttpParams();
params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
// base URL should not have ? in it at the en
return this.http.get<ResponseOrders >(this.baseUrl,{
params
}).pipe(
map(res => res.results || []),
catchError(error => _throwError(error.message || error))
);
}
Notice that you could easily transform the returned Observable
to a Promise
by simply invoking toPromise()
.
ORIGINAL ANSWER:
In your case, you can
Assumming that your backend returns something like:
{results: [{},{}]}
in JSON format, where every {} is a serialized object, you would need the following:
// Somewhere in your src folder
export interface Order {
// Properties
}
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Order } from 'somewhere_in_src';
@Injectable()
export class FooService {
ctor(private http: HttpClient){}
fetch(startIndex: number, limit: number): Observable<Order[]> {
let params = new HttpParams();
params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
// base URL should not have ? in it at the en
return this.http.get(this.baseUrl,{
params
})
.map(res => res.results as Order[] || []);
// in case that the property results in the res POJO doesnt exist (res.results returns null) then return empty array ([])
}
}
I removed the catch section, as this could be archived through a HTTP interceptor. Check the docs. As example:
https://gist.github.com/jotatoledo/765c7f6d8a755613cafca97e83313b90
And to consume you just need to call it like:
// In some component for example
this.fooService.fetch(...).subscribe(data => ...); // data is Order[]
Your file structure says that folder name is Container
with a capital C. But you are trying to import it by container
with a lowercase c. You will need to change the import or the folder name because the paths are case sensitive.
so this happened to me on windows recently. I fix it by following the following steps using a PowerShell with admin privileges:
node_modules
foldernpm install --global windows-build-tools
npm install
The answer has been given by Faisal Khurshid and Michael_B already.
This is just an attempt to make a possible solution more obvious.
For IE11 and below you need to enable grid's older specification in the parent div e.g. body or like here "grid" like so:
.grid-parent{display:-ms-grid;}
then define the amount and width of the columns and rows like e.g. so:
.grid-parent{
-ms-grid-columns: 1fr 3fr;
-ms-grid-rows: 4fr;
}
finally you need to explicitly tell the browser where your element (item) should be placed in e.g. like so:
.grid-item-1{
-ms-grid-column: 1;
-ms-grid-row: 1;
}
.grid-item-2{
-ms-grid-column: 2;
-ms-grid-row: 1;
}
If the POM missing warning is of project's self module, the reason is that you are trying to mistakenly build from a sub-module directory. You need to run the build and install command from root directory of the project.
Google Play services SDK is inside Google Repository
.
Start Intellij IDEA.
On the Tools menu, click Android > SDK Manager.
Update the Android SDK Manager: click SDK Tools, expand Support Repository, select Google Repository, and then click OK.
Current Google Repository version is 57.
After update sync your project.
EDIT
From version 11.2.0
, we've to use the google maven repo so add google maven repo link in repositories tag. Check release note from here.
allprojects {
..
repositories {
...
maven {
url 'https://maven.google.com'
// Alternative URL is 'https://dl.google.com/dl/android/maven2/'
}
}
}
The error means, that Angular doesn't know what to do when you put a formControl
on a div
.
To fix this, you have two options.
formControlName
on an element, that is supported by Angular out of the box. Those are: input
, textarea
and select
.ControlValueAccessor
interface. By doing so, you're telling Angular "how to access the value of your control" (hence the name). Or in simple terms: What to do, when you put a formControlName
on an element, that doesn't naturally have a value associated with it.Now, implementing the ControlValueAccessor
interface can be a bit daunting at first. Especially because there isn't much good documentation of this out there and you need to add a lot of boilerplate to your code. So let me try to break this down in some simple-to-follow steps.
In order to implement the ControlValueAccessor
, you need to create a new component (or directive). Move the code related to your form control there. Like this it will also be easily reusable. Having a control already inside a component might be the reason in the first place, why you need to implement the ControlValueAccessor
interface, because otherwise you will not be able to use your custom component together with Angular forms.
Implementing the ControlValueAccessor
interface is quite verbose, here's the boilerplate that comes with it:
import {Component, OnInit, forwardRef} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR} from '@angular/forms';
@Component({
selector: 'app-custom-input',
templateUrl: './custom-input.component.html',
styleUrls: ['./custom-input.component.scss'],
// a) copy paste this providers property (adjust the component name in the forward ref)
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomInputComponent),
multi: true
}
]
})
// b) Add "implements ControlValueAccessor"
export class CustomInputComponent implements ControlValueAccessor {
// c) copy paste this code
onChange: any = () => {}
onTouch: any = () => {}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouch = fn;
}
// d) copy paste this code
writeValue(input: string) {
// TODO
}
So what are the individual parts doing?
ControlValueAccessor
interfaceControlValueAccessor
interfaceonChange
and onTouch
with it's own implementation during runtime, such that you can then call those functions. So this point is important to understand: You don't need to implement onChange and onTouch yourself (other than the initial empty implementation). The only thing your doing with (c) is to let Angular attach it's own functions to your class. Why? So you can then call the onChange
and onTouch
methods provided by Angular at the appropriate time. We'll see how this works down below.writeValue
method works in the next section, when we implement it. I've put it here, so all required properties on ControlValueAccessor
are implemented and your code still compiles.What writeValue
does, is to do something inside your custom component, when the form control is changed on the outside. So for example, if you have named your custom form control component app-custom-input
and you'd be using it in the parent component like this:
<form [formGroup]="form">
<app-custom-input formControlName="myFormControl"></app-custom-input>
</form>
then writeValue
gets triggered whenever the parent component somehow changes the value of myFormControl
. This could be for example during the initialization of the form (this.form = this.formBuilder.group({myFormControl: ""});
) or on a form reset this.form.reset();
.
What you'll typically want to do if the value of the form control changes on the outside, is to write it to a local variable which represents the form control value. For example, if your CustomInputComponent
revolves around a text based form control, it could look like this:
writeValue(input: string) {
this.input = input;
}
and in the html of CustomInputComponent
:
<input type="text"
[ngModel]="input">
You could also write it directly to the input element as described in the Angular docs.
Now you have handled what happens inside of your component when something changes outside. Now let's look at the other direction. How do you inform the outside world when something changes inside of your component?
The next step is to inform the parent component about changes inside of your CustomInputComponent
. This is where the onChange
and onTouch
functions from (c) from above come into play. By calling those functions you can inform the outside about changes inside your component. In order to propagate changes of the value to the outside, you need to call onChange with the new value as the argument. For example, if the user types something in the input
field in your custom component, you call onChange
with the updated value:
<input type="text"
[ngModel]="input"
(ngModelChange)="onChange($event)">
If you check the implementation (c) from above again, you'll see what's happening: Angular bound it's own implementation to the onChange
class property. That implementation expects one argument, which is the updated control value. What you're doing now is you're calling that method and thus letting Angular know about the change. Angular will now go ahead and change the form value on the outside. This is the key part in all this. You told Angular when it should update the form control and with what value by calling onChange
. You've given it the means to "access the control value".
By the way: The name onChange
is chosen by me. You could choose anything here, for example propagateChange
or similar. However you name it though, it will be the same function that takes one argument, that is provided by Angular and that is bound to your class by the registerOnChange
method during runtime.
Since form controls can be "touched", you should also give Angular the means to understand when your custom form control is touched. You can do it, you guessed it, by calling the onTouch
function. So for our example here, if you want to stay compliant with how Angular is doing it for the out-of-the-box form controls, you should call onTouch
when the input field is blurred:
<input type="text"
[(ngModel)]="input"
(ngModelChange)="onChange($event)"
(blur)="onTouch()">
Again, onTouch
is a name chosen by me, but what it's actual function is provided by Angular and it takes zero arguments. Which makes sense, since you're just letting Angular know, that the form control has been touched.
So how does that look when it comes all together? It should look like this:
// custom-input.component.ts
import {Component, OnInit, forwardRef} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR} from '@angular/forms';
@Component({
selector: 'app-custom-input',
templateUrl: './custom-input.component.html',
styleUrls: ['./custom-input.component.scss'],
// Step 1: copy paste this providers property
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomInputComponent),
multi: true
}
]
})
// Step 2: Add "implements ControlValueAccessor"
export class CustomInputComponent implements ControlValueAccessor {
// Step 3: Copy paste this stuff here
onChange: any = () => {}
onTouch: any = () => {}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouch = fn;
}
// Step 4: Define what should happen in this component, if something changes outside
input: string;
writeValue(input: string) {
this.input = input;
}
// Step 5: Handle what should happen on the outside, if something changes on the inside
// in this simple case, we've handled all of that in the .html
// a) we've bound to the local variable with ngModel
// b) we emit to the ouside by calling onChange on ngModelChange
}
// custom-input.component.html
<input type="text"
[(ngModel)]="input"
(ngModelChange)="onChange($event)"
(blur)="onTouch()">
// parent.component.html
<app-custom-input [formControl]="inputTwo"></app-custom-input>
// OR
<form [formGroup]="form" >
<app-custom-input formControlName="myFormControl"></app-custom-input>
</form>
Note that Control Value Accessors are NOT the right tool for nested form groups. For nested form groups you can simply use an @Input() subform
instead. Control Value Accessors are meant to wrap controls
, not groups
! See this example how to use an input for a nested form: https://stackblitz.com/edit/angular-nested-forms-input-2
Install popper.js
with spesific version number like this:
bower install popper.js@^1.16.0
Now u can find dist
folder and popper.min.js
file.
Shouldn't it be just the .list-group
? See below,
<ul class="list-group">
<li class="list-group-item active">Cras justo odio</li>
<li class="list-group-item">Dapibus ac facilisis in</li>
<li class="list-group-item">Morbi leo risus</li>
<li class="list-group-item">Porta ac consectetur ac</li>
<li class="list-group-item">Vestibulum at eros</li>
</ul>
Reference: Bootstrap 4 Basic Example of a List group
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
Every class or interface can be used as a type in TypeScript.
const date = new Date();
will already know about the date
type definition as Date
is an internal TypeScript object referenced by the DateConstructor interface.
And for the constructor you used, it is defined as:
interface DateConstructor {
new(): Date;
...
}
To make it more explicit, you can use:
const date: Date = new Date();
You might be missing the type definitions though, the Date
is coming for my example from the ES6 lib, and in my tsconfig.json
I have defined:
"compilerOptions": {
"target": "ES6",
"lib": [
"es6",
"dom"
],
You might adapt these settings to target your wanted version of JavaScript.
The Date is by the way an Interface from lib.es6.d.ts
:
/** Enables basic storage and retrieval of dates and times. */
interface Date {
/** Returns a string representation of a date. The format of the string depends on the locale. */
toString(): string;
/** Returns a date as a string value. */
toDateString(): string;
/** Returns a time as a string value. */
toTimeString(): string;
/** Returns a value as a string value appropriate to the host environment's current locale. */
toLocaleString(): string;
/** Returns a date as a string value appropriate to the host environment's current locale. */
toLocaleDateString(): string;
/** Returns a time as a string value appropriate to the host environment's current locale. */
toLocaleTimeString(): string;
/** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */
valueOf(): number;
/** Gets the time value in milliseconds. */
getTime(): number;
/** Gets the year, using local time. */
getFullYear(): number;
/** Gets the year using Universal Coordinated Time (UTC). */
getUTCFullYear(): number;
/** Gets the month, using local time. */
getMonth(): number;
/** Gets the month of a Date object using Universal Coordinated Time (UTC). */
getUTCMonth(): number;
/** Gets the day-of-the-month, using local time. */
getDate(): number;
/** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */
getUTCDate(): number;
/** Gets the day of the week, using local time. */
getDay(): number;
/** Gets the day of the week using Universal Coordinated Time (UTC). */
getUTCDay(): number;
/** Gets the hours in a date, using local time. */
getHours(): number;
/** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */
getUTCHours(): number;
/** Gets the minutes of a Date object, using local time. */
getMinutes(): number;
/** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */
getUTCMinutes(): number;
/** Gets the seconds of a Date object, using local time. */
getSeconds(): number;
/** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */
getUTCSeconds(): number;
/** Gets the milliseconds of a Date, using local time. */
getMilliseconds(): number;
/** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */
getUTCMilliseconds(): number;
/** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */
getTimezoneOffset(): number;
/**
* Sets the date and time value in the Date object.
* @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.
*/
setTime(time: number): number;
/**
* Sets the milliseconds value in the Date object using local time.
* @param ms A numeric value equal to the millisecond value.
*/
setMilliseconds(ms: number): number;
/**
* Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).
* @param ms A numeric value equal to the millisecond value.
*/
setUTCMilliseconds(ms: number): number;
/**
* Sets the seconds value in the Date object using local time.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setSeconds(sec: number, ms?: number): number;
/**
* Sets the seconds value in the Date object using Universal Coordinated Time (UTC).
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setUTCSeconds(sec: number, ms?: number): number;
/**
* Sets the minutes value in the Date object using local time.
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setMinutes(min: number, sec?: number, ms?: number): number;
/**
* Sets the minutes value in the Date object using Universal Coordinated Time (UTC).
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setUTCMinutes(min: number, sec?: number, ms?: number): number;
/**
* Sets the hour value in the Date object using local time.
* @param hours A numeric value equal to the hours value.
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setHours(hours: number, min?: number, sec?: number, ms?: number): number;
/**
* Sets the hours value in the Date object using Universal Coordinated Time (UTC).
* @param hours A numeric value equal to the hours value.
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;
/**
* Sets the numeric day-of-the-month value of the Date object using local time.
* @param date A numeric value equal to the day of the month.
*/
setDate(date: number): number;
/**
* Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).
* @param date A numeric value equal to the day of the month.
*/
setUTCDate(date: number): number;
/**
* Sets the month value in the Date object using local time.
* @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
* @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.
*/
setMonth(month: number, date?: number): number;
/**
* Sets the month value in the Date object using Universal Coordinated Time (UTC).
* @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
* @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.
*/
setUTCMonth(month: number, date?: number): number;
/**
* Sets the year of the Date object using local time.
* @param year A numeric value for the year.
* @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.
* @param date A numeric value equal for the day of the month.
*/
setFullYear(year: number, month?: number, date?: number): number;
/**
* Sets the year value in the Date object using Universal Coordinated Time (UTC).
* @param year A numeric value equal to the year.
* @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.
* @param date A numeric value equal to the day of the month.
*/
setUTCFullYear(year: number, month?: number, date?: number): number;
/** Returns a date converted to a string using Universal Coordinated Time (UTC). */
toUTCString(): string;
/** Returns a date as a string value in ISO format. */
toISOString(): string;
/** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */
toJSON(key?: any): string;
}
if you're using .Net earlier than 4.5 you wont have Tls12 in the enum so state is explicitly mentioned here
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
You have to use the plugin manager of Notepad++ and search for the JSON plugin. There you can easily install it.
This answer explains it pretty good: How to reformat JSON in Notepad++?
May be i did not fully understand the problem, but, centering all view inside a ConstraintLayout seems very simple. This is what I used:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center">
Last two lines did the trick!
Using this you can avoid the loop.
// obj is the params object with key-value pair.
// This is how you convert that to HttpParams and pass this to GET API.
const params = Object.getOwnPropertyNames(obj)
.reduce((p, key) => p.set(key, obj[key]), new HttpParams());
Furthermore, I suggest making toHttpParams function in your commonly used service. So you can call the function to convert the object to the HttpParams.
/**
* Convert Object to HttpParams
* @param {Object} obj
* @returns {HttpParams}
*/
toHttpParams(obj: Object): HttpParams {
return Object.getOwnPropertyNames(obj)
.reduce((p, key) => p.set(key, obj[key]), new HttpParams());
}
Update:
Since 5.0.0-beta.6 (2017-09-03) they added new feature (accept object map for HttpClient headers & params)
Going forward the object can be passed directly instead of HttpParams.
This is the other reason if you have used one common function like toHttpParams mentioned above, you can easily remove it or do changes if required.
These both work for me in JavaScript and TypeScript
<img src="@/assets/images/logo.png" alt="">
or
<img src="./assets/images/logo.png" alt="">
In my case, since I was using TypeScript with React, the fix was simply to tell ESLint to also validate these files. This needs to go in your user settings:
"eslint.validate": [ "javascript", "javascriptreact", "html", "typescriptreact" ],
React + TypeScript inline util method:
const navigateToExternalUrl = (url: string, shouldOpenNewTab: boolean = true) =>
shouldOpenNewTab ? window.open(url, "_blank") : window.location.href = url;
Use the npm ci
command instead of npm install
.
"ci" stands for "continuous integration".
It will install the project dependencies based on the package-lock.json file instead of the lenient package.json file dependencies.
It will produce identical builds to your team mates and it is also much faster.
You can read more about it in this blog post: https://blog.npmjs.org/post/171556855892/introducing-npm-ci-for-faster-more-reliable
I follow all recommendations and all requirements. I install my self signed root CA on my iPhone. I make it trusted. I put certificate signed with this root CA on my local development server and I still get certificated error on safari iOS. Working on all other platforms.
you need to cast int to str before concatenating. for that use str(temperature)
. Or you can print the same output using ,
if you don't want to convert like this.
print("the furnace is now",temperature , "degrees!")
It's pandas
label-based selection, as explained here: https://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label
The boolean array is basically a selection method using a mask.
What finally worked for me was:
Finally worked. I have not yet re-tried with 64-bit installer, since I have a time critical project, but will do when again I have spare time.
P.S. what broke Anaconda for me was a blue screen I got while updating Anaconda. I guess it did not clear all old files and this broke the new installs.
(change)
event bound to classical input change event.
https://developer.mozilla.org/en-US/docs/Web/Events/change
You can use (change) event even if you don't have a model at your input as
<input (change)="somethingChanged()">
(ngModelChange)
is the @Output
of ngModel directive. It fires when the model changes. You cannot use this event without ngModel directive.
https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L124
As you discover more in the source code, (ngModelChange)
emits the new value.
https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L169
So it means you have ability of such usage:
<input (ngModelChange)="modelChanged($event)">
modelChanged(newObj) {
// do something with new value
}
Basically, it seems like there is no big difference between two, but ngModel
events gains the power when you use [ngValue]
.
<select [(ngModel)]="data" (ngModelChange)="dataChanged($event)" name="data">
<option *ngFor="let currentData of allData" [ngValue]="currentData">
{{data.name}}
</option>
</select>
dataChanged(newObj) {
// here comes the object as parameter
}
assume you try the same thing without "ngModel
things"
<select (change)="changed($event)">
<option *ngFor="let currentData of allData" [value]="currentData.id">
{{data.name}}
</option>
</select>
changed(e){
// event comes as parameter, you'll have to find selectedData manually
// by using e.target.data
}
the easiest way to clone an array is
backUpData = genericItems.concat();
This will create a new memory for the array indexes
Pipes in Angular 2+ are a great way to transform and format data right from your templates.
Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.
List of Built-in Pipes from API List Examples
{{ user.name | uppercase }}
Example of Angular version 4.4.7. ng version
Custom Pipes which accepts multiple arguments.
HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS « transform(json: any[], args: any[]) : any[] { ... }
Filtering the content using a Pipe « json-filter-by.pipe.ts
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {
transform(json: any[], args: any[]) : any[] {
var searchText = args[0];
var jsonKey = args[1];
// json = undefined, args = (2) [undefined, "name"]
if(searchText == null || searchText == 'undefined') return json;
if(jsonKey == null || jsonKey == 'undefined') return json;
// Copy all objects of original array into new Array.
var returnObjects = json;
json.forEach( function ( filterObjectEntery ) {
if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
console.log('Search key is available in JSON object.');
if ( typeof filterObjectEntery[jsonKey] != "undefined" &&
filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
// object value contains the user provided text.
} else {
// object didn't match a filter value so remove it from array via filter
returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
}
} else {
console.log('Search key is not available in JSON object.');
}
})
return returnObjects;
}
}
Add to @NgModule
« Add JsonFilterByPipe
to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy
. If you add to module then it is available to all the component's of that module.
@NgModule({
imports: [
CommonModule,
RouterModule,
FormsModule, ReactiveFormsModule,
],
providers: [ StudentDetailsService ],
declarations: [
UsersComponent, UserComponent,
JsonFilterByPipe,
],
exports : [UsersComponent, UserComponent]
})
export class UsersModule {
// ...
}
File Name: users.component.ts
and StudentDetailsService
is created from this link.
import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: [ './users.component.css' ],
providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy {
students: MyStudents[];
selectedStudent: MyStudents;
constructor(private studentService: StudentDetailsService) { }
ngOnInit(): void {
this.loadAllUsers();
}
ngOnDestroy(): void {
// ONDestroy to prevent memory leaks
}
loadAllUsers(): void {
this.studentService.getStudentsList().then(students => this.students = students);
}
onSelect(student: MyStudents): void {
this.selectedStudent = student;
}
}
File Name: users.component.html
<div>
<br />
<div class="form-group">
<div class="col-md-6" >
Filter by Name:
<input type="text" [(ngModel)]="searchText"
class="form-control" placeholder="Search By Category" />
</div>
</div>
<h2>Present are Students</h2>
<ul class="students">
<li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
<a *ngIf="student" routerLink="/users/update/{{student.id}}">
<span class="badge">{{student.id}}</span> {{student.name | uppercase}}
</a>
</li>
</ul>
</div>
Pod is not started due to problem coming after initialization of POD.
Check and use command to get docker container of pod
docker ps -a | grep private-reg
Output will be information of docker container with id.
See docker logs:
docker logs -f <container id>
kubeadm reset
/*On Debian base Operating systems you can use the following command.*/
# on debian base
sudo apt-get purge kubeadm kubectl kubelet kubernetes-cni kube*
/*On CentOs distribution systems you can use the following command.*/
#on centos base
sudo yum remove kubeadm kubectl kubelet kubernetes-cni kube*
# on debian base
sudo apt-get autoremove
#on centos base
sudo yum autoremove
/For all/
sudo rm -rf ~/.kube
You are creating those bytes
objects yourself:
item['title'] = [t.encode('utf-8') for t in title]
item['link'] = [l.encode('utf-8') for l in link]
item['desc'] = [d.encode('utf-8') for d in desc]
items.append(item)
Each of those t.encode()
, l.encode()
and d.encode()
calls creates a bytes
string. Do not do this, leave it to the JSON format to serialise these.
Next, you are making several other errors; you are encoding too much where there is no need to. Leave it to the json
module and the standard file object returned by the open()
call to handle encoding.
You also don't need to convert your items
list to a dictionary; it'll already be an object that can be JSON encoded directly:
class W3SchoolPipeline(object):
def __init__(self):
self.file = open('w3school_data_utf8.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
line = json.dumps(item) + '\n'
self.file.write(line)
return item
I'm guessing you followed a tutorial that assumed Python 2, you are using Python 3 instead. I strongly suggest you find a different tutorial; not only is it written for an outdated version of Python, if it is advocating line.decode('unicode_escape')
it is teaching some extremely bad habits that'll lead to hard-to-track bugs. I can recommend you look at Think Python, 2nd edition for a good, free, book on learning Python 3.
The same goes for v-for in range:
<li v-for="n in 20 " :key="n">{{n}}</li>
Are you looking for something like this?
COLUMN_NAMES=['A','B','C','D','E','F','G']
df = pd.DataFrame(columns=COLUMN_NAMES)
df.columns
Index(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='object')
you can download USBview and get all the information you need. Along with the list of devices it will also show you the configuration of each device.
You need to use the various Bootstrap 4 centering methods...
text-center
for inline elements.justify-content-center
for flexbox elements (ie; form-inline
)https://codeply.com/go/Am5LvvjTxC
Also, to offset the column, the col-sm-*
must be contained within a .row
, and the .row
must be in a container...
<section id="cover">
<div id="cover-caption">
<div id="container" class="container">
<div class="row">
<div class="col-sm-10 offset-sm-1 text-center">
<h1 class="display-3">Welcome to Bootstrap 4</h1>
<div class="info-form">
<form action="" class="form-inline justify-content-center">
<div class="form-group">
<label class="sr-only">Name</label>
<input type="text" class="form-control" placeholder="Jane Doe">
</div>
<div class="form-group">
<label class="sr-only">Email</label>
<input type="text" class="form-control" placeholder="[email protected]">
</div>
<button type="submit" class="btn btn-success ">okay, go!</button>
</form>
</div>
<br>
<a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
</div>
</div>
</div>
</div>
</section>
For quick queries you can allow room to execute it on UI thread.
AppDatabase db = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, DATABASE_NAME).allowMainThreadQueries().build();
In my case I had to figure out of the clicked user in list exists in database or not. If not then create the user and start another activity
@Override
public void onClick(View view) {
int position = getAdapterPosition();
User user = new User();
String name = getName(position);
user.setName(name);
AppDatabase appDatabase = DatabaseCreator.getInstance(mContext).getDatabase();
UserDao userDao = appDatabase.getUserDao();
ArrayList<User> users = new ArrayList<User>();
users.add(user);
List<Long> ids = userDao.insertAll(users);
Long id = ids.get(0);
if(id == -1)
{
user = userDao.getUser(name);
user.setId(user.getId());
}
else
{
user.setId(id);
}
Intent intent = new Intent(mContext, ChatActivity.class);
intent.putExtra(ChatActivity.EXTRAS_USER, Parcels.wrap(user));
mContext.startActivity(intent);
}
}
I have created this Plunker based on your example that updates the object equal to newItem.id
Here's the snippet of my functions:
showUpdatedItem(newItem){
let updateItem = this.itemArray.items.find(this.findIndexToUpdate, newItem.id);
let index = this.itemArray.items.indexOf(updateItem);
this.itemArray.items[index] = newItem;
}
findIndexToUpdate(newItem) {
return newItem.id === this;
}
Hope this helps.
as long as you did not commit you can type
git merge --abort
just as the command line suggested.
You have to change
loadNavItems() {
this.navItems = this.http.get("../data/navItems.json");
console.log(this.navItems);
}
for
loadNavItems() {
this.navItems = this.http.get("../data/navItems.json")
.map(res => res.json())
.do(data => console.log(data));
//This is optional, you can remove the last line
// if you don't want to log loaded json in
// console.
}
Because this.http.get
returns an Observable<Response>
and you don't want the response, you want its content.
The console.log
shows you an observable, which is correct because navItems contains an Observable<Response>
.
In order to get data properly in your template, you should use async
pipe.
<app-nav-item-comp *ngFor="let item of navItems | async" [item]="item"></app-nav-item-comp>
This should work well, for more informations, please refer to HTTP Client documentation
Use the in
keyword.
if 'apples' in d:
if d['apples'] == 20:
print('20 apples')
else:
print('Not 20 apples')
If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get
function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None
instead):
if d.get('apples', 0) == 20:
print('20 apples.')
else:
print('Not 20 apples.')
Post Django version 1.9,
on_delete
became a required argument, i.e. from Django 2.0.
In older versions, it defaults to CASCADE.
So, if you want to replicate the functionality that you used in earlier versions. Use the following argument.
categorie = models.ForeignKey('Categorie', on_delete = models.CASCADE)
This will have the same effect as that was in earlier versions, without specifying it explicitly.
Official Documentation on other arguments that go with on_delete
You can access Globals
entity from any point of your App via Angular dependency injection. If you want to output Globals.role
value in some component's template, you should inject Globals
through the component's constructor like any service:
// hello.component.ts
import { Component } from '@angular/core';
import { Globals } from './globals';
@Component({
selector: 'hello',
template: 'The global role is {{globals.role}}',
providers: [ Globals ] // this depends on situation, see below
})
export class HelloComponent {
constructor(public globals: Globals) {}
}
I provided Globals
in the HelloComponent
, but instead it could be provided in some HelloComponent's
parent component or even in AppModule
. It will not matter until your Globals
has only static data that could not be changed (say, constants only). But if it's not true and for example different components/services might want to change that data, then the Globals
must be a singleton. In that case it should be provided in the topmost level of the hierarchy where it is going to be used. Let's say this is AppModule
:
import { Globals } from './globals'
@NgModule({
// ... imports, declarations etc
providers: [
// ... other global providers
Globals // so do not provide it into another components/services if you want it to be a singleton
]
})
Also, it's impossible to use var the way you did, it should be
// globals.ts
import { Injectable } from '@angular/core';
@Injectable()
export class Globals {
role: string = 'test';
}
Update
At last, I created a simple demo on stackblitz, where single Globals
is being shared between 3 components and one of them can change the value of Globals.role
.
When you do new Promise((resolve)...
the type inferred was Promise<{}>
because you should have used new Promise<number>((resolve)
.
It is interesting that this issue was only highlighted when the async
keyword was added. I would recommend reporting this issue to the TS team on GitHub.
There are many ways you can get around this issue. All the following functions have the same behavior:
const whatever1 = () => {
return new Promise<number>((resolve) => {
resolve(4);
});
};
const whatever2 = async () => {
return new Promise<number>((resolve) => {
resolve(4);
});
};
const whatever3 = async () => {
return await new Promise<number>((resolve) => {
resolve(4);
});
};
const whatever4 = async () => {
return Promise.resolve(4);
};
const whatever5 = async () => {
return await Promise.resolve(4);
};
const whatever6 = async () => Promise.resolve(4);
const whatever7 = async () => await Promise.resolve(4);
In your IDE you will be able to see that the inferred type for all these functions is () => Promise<number>
.
Hi @daniel.lozynski. Access-Control-Allow-Origin
is one of the worst problems web developers face when working with APIs, and I've been working on solutions for a long time.
One way to get rid of Access-Control-Allow-Origin
is to use proxies. Of course, proxies sometimes have their own problems.
too many requests
error. Of course, this problem is eliminated by switching between proxies.However, these are all temporary problems and only occur to you during development.
Below is a list of the best proxies I have ever found.
You can easily equip the API with a proxy and get rid of Access-Control-Allow-Origin
by adding any of these addresses before your IP address.
Consider a few examples below:
Use of proxies is limited to online APIs. And you can not use proxies in local APIs. In the following, I will tell you to answer for local APIs as well...
I recently came across a very good Chrome extension that has not had those two proxy problems for me so far and I am very happy with it since I used it.
But the only problem with using this plugin is that you can no longer debug your project on your mobile phone with IP address. This is because this plugin only creates a proxy on your browser and no longer affects data transmission over cable by IP.
You can find and install this plugin from this link.
Allow CORS: Access-Control-Allow-Origin
You can just install this extension on your Chrome browser and have fun...!
Using this plugin is very, very simple and you just need to install it and then activate it. However, if you have a problem with it, on the page of this plugin in 'Chrome Extensions', there is a YouTube video that will completely solve your problems by watching it.
Because my favorite browser is to develop Chrome, I did not look for solutions for other extensions. So if you use Chrome, this plugin will be very useful for you as well.
<select v-model="challan.warehouse_id">
<option value="">Select Warehouse</option>
<option v-for="warehouse in warehouses" v-bind:value="warehouse.id" >
{{ warehouse.name }}
</option>
Here "challan.warehouse_id" come from "challan" object you get from:
editChallan: function() {
let that = this;
axios.post('/api/challan_list/get_challan_data', {
challan_id: that.challan_id
})
.then(function (response) {
that.challan = response.data;
})
.catch(function (error) {
that.errors = error;
});
}
Actually, would be better to isolate this resize logic in a custom hook. You can create a custom hook like this:
const useResize = (myRef) => {
const [width, setWidth] = useState(0)
const [height, setHeight] = useState(0)
useEffect(() => {
const handleResize = () => {
setWidth(myRef.current.offsetWidth)
setHeight(myRef.current.offsetHeight)
}
window.addEventListener('resize', handleResize)
return () => {
window.removeEventListener('resize', handleResize)
}
}, [myRef])
return { width, height }
}
and then you can use it like:
const MyComponent = () => {
const componentRef = useRef()
const { width, height } = useResize(componentRef)
return (
<div ref={myRef}>
<p>width: {width}px</p>
<p>height: {height}px</p>
<div/>
)
}
This seems to be the cleanest way to do
if (foo === 1) {
} else if (bar === 99) {
} else if (foo === 2) {
} else {
}
in the template:
<ng-container *ngIf="foo === 1; else elseif1">foo === 1</ng-container>
<ng-template #elseif1>
<ng-container *ngIf="bar === 99; else elseif2">bar === 99</ng-container>
</ng-template>
<ng-template #elseif2>
<ng-container *ngIf="foo === 2; else else1">foo === 2</ng-container>
</ng-template>
<ng-template #else1>else</ng-template>
Notice that it works like a proper else if
statement should when the conditions involve different variables (only 1 case is true at a time). Some of the other answers don't work right in such a case.
aside: gosh angular, that's some really ugly else if
template code...
Suppose you bound your combobox to a List<Person>
List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource
pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;
Of course this means that you need to add a checking code when you try to use the info from the combobox
if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
MessageBox.Show("Please select a person name");
else
......
The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection
In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to
DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);
Besides the redundant )
this expression will always be true
because currentStatus
will always match one of these two conditions:
currentStatus !== 'open' || currentStatus !== 'reopen'
perhaps you mean one of
!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')
Solutions in accepted answer are being deprecated
#4 Calling prop directly
Enzyme simulate is supposed to be removed in version 4. The main maintainer is suggesting directly invoking prop functions, which is what simulate does internally. One solution is to directly test that invoking those props does the right thing; or you can mock out instance methods, test that the prop functions call them, and unit test the instance methods.
You could call click, for example:
wrapper.find('Button').prop('onClick')()
Or
wrapper.find('Button').props().onClick()
Information about deprecation: Deprecation of .simulate() #2173
simply put in headers 'Content-Type': 'application/json'
and the sent data in body JSON.stringify(string)
I had the same issue and here is how I manage to pass through:
In your case you have addToCount()
which is called. now to pass down a param when user clicks, you can say @click="addToCount(item.contactID)"
in your function implementation you can receive the params like:
addToCount(paramContactID){
// the paramContactID contains the value you passed into the function when you called it
// you can do what you want to do with the paramContactID in here!
}
Yet another reason may be that your entity class has several properties named somhow /.*id/i
- so ending with ID case insensitive AND elementary type AND there is no [Key]
attribute.
EF will namely try to figure out the PK by itself by looking for elementary typed properties ending in ID.
See my case:
public class MyTest, IMustHaveTenant
{
public long Id { get; set; }
public int TenantId { get; set; }
[MaxLength(32)]
public virtual string Signum{ get; set; }
public virtual string ID { get; set; }
public virtual string ID_Other { get; set; }
}
don't ask - lecacy code. The Id
was even inherited, so I could not use [Key]
(just simplifying the code here)
But here EF is totally confused.
What helped was using modelbuilder this in DBContext class.
modelBuilder.Entity<MyTest>(f =>
{
f.HasKey(e => e.Id);
f.HasIndex(e => new { e.TenantId });
f.HasIndex(e => new { e.TenantId, e.ID_Other });
});
the index on PK is implicit.
Solution for linux and specifically Ubuntu 20:04. First ensure you have Java installed before proceeding:
1. java -version
2. sudo apt-get update
3. sudo apt-get install openjdk-8-jdk
Open .bashrc
vim $HOME/.bashrc
Set Java environment variables.
export JAVA_HOME="/usr/lib/jvm/java-1.8.0-openjdk-amd64"
export JRE_HOME="/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre"
Visit Gradle's website and identify the version you would like to install. Replace version 6.5.1 with the version number you would like to install.
1. sudo apt-get update
2. cd /tmp && curl -L -O https://services.gradle.org/distributions/gradle-6.5.1-bin.zip
3. sudo mkdir /opt/gradle
4. sudo unzip -d /opt/gradle /tmp/gradle-6.5.1-bin.zip
To setup Gradle's environment variables use nano or vim or gedit editors to create a new file:
sudo vim /etc/profile.d/gradle.sh
Add the following lines to gradle.sh
export GRADLE_HOME="/opt/gradle/gradle-6.5.1/"
export PATH=${GRADLE_HOME}/bin:${PATH}
Run the following commands to make gradle.sh executable and to update your bash terminal with the environment variables you set as well as check the installed version.
1. sudo chmod +x /etc/profile.d/gradle.sh
3. source /etc/profile.d/gradle.sh
4. gradle -v
The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr)
instead of 1fr
as your track size.
In general, the error ValueError: Wrong number of items passed 3, placement implies 1
suggests that you are attempting to put too many pigeons in too few pigeonholes. In this case, the value on the right of the equation
results['predictedY'] = predictedY
is trying to put 3 "things" into a container that allows only one. Because the left side is a dataframe column, and can accept multiple items on that (column) dimension, you should see that there are too many items on another dimension.
Here, it appears you are using sklearn for modeling, which is where gaussian_process.GaussianProcess()
is coming from (I'm guessing, but correct me and revise the question if this is wrong).
Now, you generate predicted values for y here:
predictedY, MSE = gp.predict(testX, eval_MSE = True)
However, as we can see from the documentation for GaussianProcess, predict()
returns two items. The first is y, which is array-like (emphasis mine). That means that it can have more than one dimension, or, to be concrete for thick headed people like me, it can have more than one column -- see that it can return (n_samples, n_targets)
which, depending on testX
, could be (1000, 3)
(just to pick numbers). Thus, your predictedY
might have 3 columns.
If so, when you try to put something with three "columns" into a single dataframe column, you are passing 3 items where only 1 would fit.
if you use sass, you can try this
&::-webkit-scrollbar {
}
Use either auto-fill
or auto-fit
as the first argument of the repeat()
notation.
<auto-repeat>
variant of the repeat()
notation:
repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
auto-fill
When
auto-fill
is given as the repetition number, if the grid container has a definite size or max size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, 186px);
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
The grid will repeat as many tracks as possible without overflowing its container.
In this case, given the example above (see image), only 5 tracks can fit the grid-container without overflowing. There are only 4 items in our grid, so a fifth one is created as an empty track within the remaining space.
The rest of the remaining space, track #6, ends the explicit grid. This means there was not enough space to place another track.
auto-fit
The
auto-fit
keyword behaves the same asauto-fill
, except that after grid item placement any empty repeated tracks are collapsed.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, 186px);
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
The grid will still repeat as many tracks as possible without overflowing its container, but the empty tracks will be collapsed to 0
.
A collapsed track is treated as having a fixed track sizing function of 0px
.
Unlike the auto-fill
image example, the empty fifth track is collapsed, ending the explicit grid right after the 4th item.
auto-fill
vs auto-fit
The difference between the two is noticeable when the minmax()
function is used.
Use minmax(186px, 1fr)
to range the items from 186px
to a fraction of the leftover space in the grid container.
When using auto-fill
, the items will grow once there is no space to place empty tracks.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
When using auto-fit
, the items will grow to fill the remaining space because all the empty tracks will be collapsed to 0px
.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(186px, 1fr));
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
Playground:
Inspecting auto-fill tracks
Inspecting auto-fit tracks
In my case it was a package that was installed as a dependency in package.json
with a relative path like this:
"dependencies": {
...
"phoenix_html": "file:../deps/phoenix_html"
},
and imported in js/app.js
with import "phoenix_html"
This had worked but after an update of node, npm, etc... it failed with the above error-message.
Changing the import line to import "../../deps/phoenix_html"
fixed it.
Forgetting to make the test class public prevents the test methods inside to be discovered.
I had a default xUnit project and deleted the sample UnitTest1.cs, replacing it with a controller test class, with a couple of tests, but none were found.
Long story short, after updating xUnit, Test.Sdk, xUnit.runner packages and rebuilding the project, I encountered a build error:
Error xUnit1000 Test classes must be public
Thankfully, the updated version threw this exception to spare me some trouble.
Modifying the test class to be public fixed my issue.
The solution was as simple as adding plt.show()
at the end of the code snippet:
import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
print X_train.shape
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()
One alternative - and more lightweight approach to your problem - might be, just editing the array temporarily and then assigning the whole array back to your variable. Because as Vue does not watch individual items it will watch the whole variable being updated.
So you this should work as well:
var tempArray[];
tempArray = this.items;
tempArray[targetPosition] = value;
this.items = tempArray;
This then should also update your DOM.
If you are using CORS middleware and you want to send withCredentials
boolean true, you can configure CORS like this:
var cors = require('cors'); _x000D_
app.use(cors({credentials: true, origin: 'http://localhost:5000'}));
_x000D_
`
The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).
You can use the GUI to do the installation, or you can script the installation of msbuild:
vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet
Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:
You can find documentation about the other available CLI switches here.
The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet
there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin
.
If you don't see them there, try running without --quiet
to see any error messages that may occur during installation.
I had the same error pop up in VS 2017 when trying to delete a remote branch. The issue was that the branch was not on the server (using TFS2018 with GIT), but somehow Visual Studio did have it show up in the "remote/origin" section. This meant that I could not delete the remote branch (VS was giving out this error, while the server explorer didn't show up the branch at all).
Here's how to fix it (tested in VS 2017):
Hopefully it will help someone who ends up on this thread having the same issue as me.
I have used the exact steps from here and it worked flawlessly : https://docs.microsoft.com/en-us/visualstudio/install/install-vs-inconsistent-quality-network
In 3 simple steps:
Step 1 : Download the respective Visual Studio 2017 version from the download page (https://www.visualstudio.com/downloads/)
Step 2: Open your command prompt as Administarator, point to where your Visual studio download exe is and execute the following command (this command is specifically for Web & Desktop development) :
vs_community.exe --layout c:\vs2017layout --add Microsoft.VisualStudio.Workload.ManagedDesktop --add Microsoft.VisualStudio.Workload.NetWeb --add Component.GitHub.VisualStudio --includeOptional --lang en-US
Step 3 : Traverse to the path c:\vs2017layout in your command prompt and then run the following command (this command is specifically for Web & Desktop development)
vs_community.exe --add Microsoft.VisualStudio.Workload.ManagedDesktop --add Microsoft.VisualStudio.Workload.NetWeb --add Component.GitHub.VisualStudio --includeOptional
If you are running it on localhost change the port to 5000 and it will fix it
Equal height columns is the default behaviour for Bootstrap 4 grids.
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
<br>_x000D_
Line 2_x000D_
<br>_x000D_
Line 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Try adding this at the end of your code:
import matplotlib.pyplot as plt
plt.title('add title here')
I am required to show form vertically center inside container-fluid so I developed my own code for the same.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<style>
.container-fluid
{
display: table-cell;
height: 100vh;
width: 100vw !important;
vertical-align: middle;
border:1px solid black;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-8 offset-2">
<div class="card shadow">
<div class="card-header bg-danger text-white">
<h2>Login</h2>
</div>
<div class="card-body">
<form action="">
<div class="form-group row">
<label for="txtemail" class="col-form-label col-sm-2">Email</label>
<div class="col-sm-10">
<input type="email" name="txtemail" id="txtemail" class="form-control" required />
</div>
</div>
<div class="form-group row">
<label for="txtpassword" class="col-form-label col-sm-2">Password</label>
<div class="col-sm-10">
<input type="password" name="txtpassword" id="txtpassword" class="form-control"
required />
</div>
</div>
<div class="form-group">
<button class="btn btn-danger btn-block">Login</button>
<button class="btn btn-warning btn-block">clear all</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="js/jquery.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
npm install --unsafe-perm
worked for me. See https://docs.npmjs.com/. The --unsafe-perm
parameter lets you run the scripts from the package instalation as root. The problem in my case was that some depandencies failed to install.
Louis' answer is great, but I thought I would try to sum it up succinctly:
The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".
Just right click on the ConstrainLayout and select the "convert view" and then "RelativeLayout":
You probably want to assign the lastname
you are reading out here
lastname = sheet.cell(row=r, column=3).value
to something; currently the program just forgets it
you could do that two lines after, like so
unpaidMembers[name] = lastname, email
your program will still crash at the same place, because .items()
still won't give you 3-tuples but rather something that has this structure: (name, (lastname, email))
good news is, python can handle this
for name, (lastname, email) in unpaidMembers.items():
etc.
Use FractionallySizedBox
widget.
FractionallySizedBox(
widthFactor: 1.0, // width w.r.t to parent
heightFactor: 1.0, // height w.r.t to parent
child: *Your Child Here*
}
This widget is also very useful when you want to size your child at a fractional of its parent's size.
Example:
If you want the child to occupy 50% width of its parent, provide
widthFactor
as0.5
In Bootstrap 4 (beta), use align-middle
. Refer to Bootstrap 4 Documentation on Vertical alignment:
Change the alignment of elements with the vertical-alignment utilities. Please note that vertical-align only affects inline, inline-block, inline-table, and table cell elements.
Choose from
.align-baseline
,.align-top
,.align-middle
,.align-bottom
,.align-text-bottom
, and.align-text-top
as needed.
I also noticed that you can provide a group of coroutines in wait() by simply specifying the list:
result=loop.run_until_complete(asyncio.wait([
say('first hello', 2),
say('second hello', 1),
say('third hello', 4)
]))
Whereas grouping in gather() is done by just specifying multiple coroutines:
result=loop.run_until_complete(asyncio.gather(
say('first hello', 2),
say('second hello', 1),
say('third hello', 4)
))
I got this error resolved by doing 2 things in chrome browser:
This site has this information and other options as well : https://www.thesslstore.com/blog/fix-err-ssl-protocol-error/
Personally I prefer this clean implementation:
watch: {
myVariable: {
handler(newVal, oldVal){ // here having access to the new and old value
// do stuff
},
deep: true,
immediate: true // Also very important the immediate in case you need it, the callback will be called immediately after the start of the observation
}
}
I found a faster way of embedding:
I saw this message using angular, so i just took method="post" and action="" out, and the warning was gone.
Yet another idea to throw in to the mix... In my case, the component throwing the error was a template-less component with a custom render()
function. I couldn't see why it wasn't working, until I realised that I hadn't put <script>
...</script>
tags around the code in the component (seemed unnecessary, since I had no template or style tags either). Not sure why this got past the compiler...?
Either way... make sure you use your <script>
tags ;-)
Just add <br>
where you would like to make the new line.
$S$: a set of shops
<br>
$I$: a set of items M wants to get
Because jupyter notebook markdown cell is a superset of HTML.
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html
Note that newlines using <br>
does not persist when exporting or saving the notebook to a pdf (using "Download as > PDF via LaTeX"). It is probably treating each <br>
as a space.
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.
The answer above not work for me. I just solved it by appending the absolute path of the module which not found to the sys.path
at top of the test_xxx.py
(your test module), like:
import sys
sys.path.append('path')
The best and easiest way is auto-py-to-exe for sure, and I have given all the steps and red flags below which will take you just 5 mins to get a final .exe file as you don't have to learn anything to use it.
1.) It may not work for python 3.9 on some devices I guess.
2.) While installing python, if you had selected 'add python 3.x to path', open command prompt from start menu and you will have to type pip install auto-py-to-exe
to install it. You will have to press enter on command prompt to get the result of the line that you are typing.
3.) Once it is installed, on command prompt itself, you can simply type just auto-py-to-exe
to open it. It will open a new window. It may take up to a minute the first time. Also, closing command prompt will close auto-py-to-exe also so don't close it till you have your .exe file ready.
4.) There will be buttons for everything you need to make a .exe file and the screenshot of it is shared below. Also, for the icon, you need a .ico file instead of an image so to convert it, you can use https://convertio.co/
5.) If your script uses external files, you can add them through auto-py-to-exe and in the script, you will have to do some changes to their path. First, you have to write import sys
if not written already, second, you have to make a variable for eg, location=getattr(sys,"_MEIPASS",".")+"/"
, third, the location of example.png would be location+"/example.png"
if it is not in any folder.
6.) If it is showing any error, it may probably be because of a module called setuptools not being at the latest version. To upgrade it to the latest version, on command prompt, you will have to write pip install --upgrade setuptools
. Also, in the script, writing import setuptools
may help. If the version of setuptools is more than 50.0.0 then everything should be fine.
7.) After all these steps, in auto-py-to-exe, when the conversion is complete, the .exe file will be in the folder that you would have chosen (by default, it is 'c:/users/name/output') or it would have been removed by your antivirus if you have one. Every antivirus has different methods to restore a file so just experiment if you don't know.
Here is how the simple GUI of auto-py-to-exe can be used to make a .exe file.
Kotlin for XML
app:cardBackgroundColor="@android:color/red"
code
cardName.setCardBackgroundColor(ContextCompat.getColor(this, R.color.colorGray));
I was having this problem and none of the solutions in SO helped. I figured it out so I am posting it here in case any one else has a similar issue.
I was trying to run npm i on an amazon instance. The problem ended up being the fact that linux only opens up a certain amount of ports, and when npm i runs, it opens like more than a thousand connects to the registry to download all the packages. So it would work but then just freeze for like 15 minutes. Then the timeout would occur and it would eventually move on to another port. So in my security group in AWS I added a rule for All TCP at 0.0.0.0/0 in outgoing only, letting npm open as many outgoing connections as it likes and that fixed it.
This solution is only for components
If we toggle(show/hide) components using booleans then data is also removed. No need to clean the form fields.
I usually make components and initialize them using booleans. e.g.
<template>
<button @click="show_create_form = true">Add New Record</button
<create-form v-if="show_create_form" />
</template>
<script>
...
data(){
return{
show_create_form:false //making it false by default
}
},
methods:{
submitForm(){
//...
this.axios.post('/submit-form-url',data,config)
.then((response) => {
this.show_create_form= false; //hide it again after success.
//if you now click on add new record button then it will show you empty form
}).catch((error) => {
//
})
}
}
...
</script>
When use clicks on edit button then this boolean becomes true and after successful submit I change it to false again.
In my case, I wanted just one set of navigation buttons / options and found that this will work:
<div class="collapse navbar-collapse justify-content-end" id="navbarCollapse">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Sign Out</a>
</li>
</ul>
</div>
So, you will add justify-content-end
to the div and omit mr-auto
on the list.
Here is a working example.
Remove :
npm uninstall -g angular-cli
Reinstall (with yarn)
# npm install --global yarn
yarn global add @angular/cli@latest
ng set --global packageManager=yarn # This will help ng-cli to use yarn
Reinstall (with npm)
npm install --global @angular/cli@latest
Another way is to not use global install, and add /node_modules/.bin
folder in the PATH, or use npm scripts. It will be softer to upgrade.
You can do it in two ways:
First:
render() {
const data =[{"name":"test1"},{"name":"test2"}];
const listItems = data.map((d) => <li key={d.name}>{d.name}</li>);
return (
<div>
{listItems }
</div>
);
}
Second: Directly write the map function in the return
render() {
const data =[{"name":"test1"},{"name":"test2"}];
return (
<div>
{data.map(function(d, idx){
return (<li key={idx}>{d.name}</li>)
})}
</div>
);
}
This worked for me and also worked with bootstrap tables
<style>
.table td, .table th {
font-size: 10px;
}
</style>
After some research and testing, I found that I had some misunderstandings about the lifetime of Docker containers. Simply restarting a container doesn't make Docker use a new image, when the image was rebuilt in the meantime. Instead, Docker is fetching the image only before creating the container. So the state after running a container is persistent.
Therefore, rebuilding and restarting isn't enough. I thought containers works like a service: Stopping the service, do your changes, restart it and they would apply. That was my biggest mistake.
Because containers are permanent, you have to remove them using docker rm <ContainerName>
first. After a container is removed, you can't simply start it by docker start
. This has to be done using docker run
, which itself uses the latest image for creating a new container-instance.
With this knowledge, it's comprehensible why storing data in containers is qualified as bad practice and Docker recommends data volumes/mounting host directorys instead: Since a container has to be destroyed to update applications, the stored data inside would be lost too. This cause extra work to shutdown services, backup data and so on.
So it's a smart solution to exclude those data completely from the container: We don't have to worry about our data, when its stored safely on the host and the container only holds the application itself.
-rf
may not really help youThe docker run
command, has a Clean up switch called -rf
. It will stop the behavior of keeping docker containers permanently. Using -rf
, Docker will destroy the container after it has been exited. But this switch has two problems:
-d
switchWhile the -rf
switch is a good option to save work during development for quick tests, it's less suitable in production. Especially because of the missing option to run a container in the background, which would mostly be required.
We can bypass those limitations by simply removing the container:
docker rm --force <ContainerName>
The --force
(or -f
) switch which use SIGKILL on running containers. Instead, you could also stop the container before:
docker stop <ContainerName>
docker rm <ContainerName>
Both are equal. docker stop
is also using SIGTERM. But using --force
switch will shorten your script, especially when using CI servers: docker stop
throws an error if the container is not running. This would cause Jenkins and many other CI servers to consider the build wrongly as failed. To fix this, you have to check first if the container is running as I did in the question (see containerRunning
variable).
According to this new knowledge, I fixed my script in the following way:
#!/bin/bash
imageName=xx:my-image
containerName=my-container
docker build -t $imageName -f Dockerfile .
echo Delete old container...
docker rm -f $containerName
echo Run new container...
docker run -d -p 5000:5000 --name $containerName $imageName
This works perfectly :)
// @HostListener('scroll', ['$event']) // for scroll events of the current element
@HostListener('window:scroll', ['$event']) // for window scroll events
onScroll(event) {
...
}
or
<div (scroll)="onScroll($event)"></div>
In your second statement
import {FriendCard} from './../pages/FriendCard'
you are telling typescript to import the FriendCard class from the file './pages/FriendCard'
Your FriendCard file is exporting a variable and that variable is referencing the anonymous function.
You have two options here. If you want to do this in a typed way you can refactor your module to be typed (option 1) or you can import the anonymous function and add a d.ts file. See https://github.com/Microsoft/TypeScript/issues/3019 for more details. about why you need to add the file.
Refactor the Friend card js file to be typed.
export class FriendCard {
webElement: any;
menuButton: any;
serialNumber: any;
constructor(card) {
this.webElement = card;
this.menuButton;
this.serialNumber;
}
getAsWebElement = function () {
return this.webElement;
};
clickMenuButton = function () {
this.menuButton.click();
};
setSerialNumber = function (numberOfElements) {
this.serialNumber = numberOfElements + 1;
this.menuButton = element(by.xpath('.//*[@id=\'mCSB_2_container\']/li[' + serialNumber + ']/ng-include/div/div[2]/i'));
};
deleteFriend = function () {
element(by.css('[ng-click="deleteFriend(person);"]')).click();
element(by.css('[ng-click="confirm()"]')).click();
}
};
You can import the anonymous function
import * as FriendCard from module("./FriendCardJs");
There are a few options for a d.ts file definition. This answer seems to be the most complete: How do you produce a .d.ts "typings" definition file from an existing JavaScript library?
@Bashir almost helped me but I needed:
composer update --no-scripts
I found the answer here: https://laracasts.com/discuss/channels/general-discussion/fatal-error-class-illuminatefoundationapplication-not-found-in-pathtoprojectbootstrapappphp-on-line-14?page=0
Elliot Beach is correct. Thanks Elliot.
Here is the code from my gist.
sudo apt-get remove docker docker-engine docker.io
sudo apt-get update
sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo apt-key fingerprint 0EBFCD88
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
xenial \
stable"
sudo apt-get update
sudo apt-get install docker-ce
sudo docker run hello-world
python -m pip install Pillow
Will use pip of current Python activated with
source activate shrink_venv
Try curl -v http://localhost:8080/
instead of 127.0.0.1
Ref and event bus both has issues when your control render is affected by v-if
. So, I decided to go with a simpler method.
The idea is using an array as a queue to send methods that needs to be called to the child component. Once the component got mounted, it will process this queue. It watches the queue to execute new methods.
(Borrowing some code from Desmond Lua's answer)
Parent component code:
import ChildComponent from './components/ChildComponent'
new Vue({
el: '#app',
data: {
item: {},
childMethodsQueue: [],
},
template: `
<div>
<ChildComponent :item="item" :methods-queue="childMethodsQueue" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.childMethodsQueue.push({name: ChildComponent.methods.save.name, params: {}})
}
},
components: { ChildComponent },
})
This is code for ChildComponent
<template>
...
</template>
<script>
export default {
name: 'ChildComponent',
props: {
methodsQueue: { type: Array },
},
watch: {
methodsQueue: function () {
this.processMethodsQueue()
},
},
mounted() {
this.processMethodsQueue()
},
methods: {
save() {
console.log("Child saved...")
},
processMethodsQueue() {
if (!this.methodsQueue) return
let len = this.methodsQueue.length
for (let i = 0; i < len; i++) {
let method = this.methodsQueue.shift()
this[method.name](method.params)
}
},
},
}
</script>
And there is a lot of room for improvement like moving processMethodsQueue
to a mixin...
async function main() {
var getQuoteError
var quote = await getQuote().catch(err => { getQuoteError = err }
if (getQuoteError) return console.error(err)
console.log(quote)
}
Alternatively instead of declaring a possible var to hold an error at the top you can do
if (quote instanceof Error) {
// ...
}
Though that won't work if something like a TypeError or Reference error is thrown. You can ensure it is a regular error though with
async function main() {
var quote = await getQuote().catch(err => {
console.error(err)
return new Error('Error getting quote')
})
if (quote instanceOf Error) return quote // get out of here or do whatever
console.log(quote)
}
My preference for this is wrapping everything in a big try-catch block where there's multiple promises being created can make it cumbersome to handle the error specifically to the promise that created it. With the alternative being multiple try-catch blocks which I find equally cumbersome
When you install python3
, pip3
gets installed. And if you don't have another python installation(like python2.7) then a link is created which points pip
to pip3
.
So pip
is a link to to pip3
if there is no other version of python installed(other than python3).
pip
generally points to the first installation.
I was getting this error for a different reason than those listed here, and could not find the solution easily, so I figured I would post here.
Hopefully this is helpful to someone.
My issue was with referencing files in the program. It was not able to find the file listed, because when I was coding it I had the file I wanted to reference in the top level directory and just called
"my_file.png"
when I was calling the files.
pyinstaller did not like this, because even when I was running it from the same folder, it was expecting a full path:
"C:\Files\my_file.png"
Once I changed all of my paths, to the full version of their path, it fixed this issue.
You can use embed player with opacity over on a cover photo with a right positioned play icon. After this you can check the activeElement of your document.
Of course I know this is not an optimal solution, but works on mobile devices too.
<div style="position: relative;">
<img src="http://s3.amazonaws.com/content.newsok.com/newsok/images/mobile/play_button.png" style="position:absolute;top:0;left:0;opacity:1;" id="cover">
<iframe width="560" height="315" src="https://www.youtube.com/embed/2qhCjgMKoN4?controls=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in- picture" allowfullscreen style="position: absolute;top:0;left:0;opacity:0;" id="player"></iframe>
</div>
<script>
setInterval(function(){
if(document.activeElement instanceof HTMLIFrameElement){
document.getElementById('cover').style.opacity=0;
document.getElementById('player').style.opacity=1;
}
} , 50);
</script>
Try it on codepen: https://codepen.io/sarkiroka/pen/OryxGP
This code nearly worked for me...but I wanted a multiple element filter so my mods to the filter pipe are below:
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {
transform(json: any[], args: any[]): any[] {
const searchText = args[0];
const jsonKey = args[1];
let jsonKeyArray = [];
if (searchText == null || searchText === 'undefined') { return json; }
if (jsonKey.indexOf(',') > 0) {
jsonKey.split(',').forEach( function(key) {
jsonKeyArray.push(key.trim());
});
} else {
jsonKeyArray.push(jsonKey.trim());
}
if (jsonKeyArray.length === 0) { return json; }
// Start with new Array and push found objects onto it.
let returnObjects = [];
json.forEach( function ( filterObjectEntry ) {
jsonKeyArray.forEach( function (jsonKeyValue) {
if ( typeof filterObjectEntry[jsonKeyValue] !== 'undefined' &&
filterObjectEntry[jsonKeyValue].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
// object value contains the user provided text.
returnObjects.push(filterObjectEntry);
}
});
});
return returnObjects;
}
}
Now, instead of
jsonFilterBy:[ searchText, 'name']
you can do
jsonFilterBy:[ searchText, 'name, other, other2...']
Eric's answer helpfully explains that the trouble comes from comparing a Pandas Series (containing a NumPy array) to a Python string. Unfortunately, his two workarounds both just suppress the warning.
To write code that doesn't cause the warning in the first place, explicitly compare your string to each element of the Series and get a separate bool for each. For example, you could use map
and an anonymous function.
myRows = df[df['Unnamed: 5'].map( lambda x: x == 'Peter' )].index.tolist()
Here's a much newer Kotlin solution for this which is much simpler than many of the answers written here, it uses anonymous class.
val items = mutableListOf<String>()
inner class ItemHolder(view: View): RecyclerView.ViewHolder(view) {
var textField: TextView = view.findViewById(android.R.id.text1) as TextView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
rvitems.layoutManager = LinearLayoutManager(context)
rvitems.adapter = object : RecyclerView.Adapter<ItemHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
return ItemHolder(LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false))
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ItemHolder, position: Int) {
holder.textField.text = items[position]
holder.textField.setOnClickListener {
Toast.makeText(context, "Clicked $position", Toast.LENGTH_SHORT).show()
}
}
}
}
I took the liberty to use android.R.layout.simple_list_item_1 as it's simpler. I wanted to simplify it even further and put ItemHolder as an inner class but couldn't quite figure out how to reference it in a type in the outer class parameter.
something like this?
#sticky-sidebar {_x000D_
position:fixed;_x000D_
max-width: 20%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-xs-4">_x000D_
<div class="col-xs-12" id="sticky-sidebar">_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</div>_x000D_
</div>_x000D_
<div class="col-xs-8" id="main">_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</div>_x000D_
</div>_x000D_
</div
_x000D_
disabling of mat form fields is exempted if you are using form validation,so do make sure that your form field does not have any validations like(validators.required),this worked for me. for ex:
editUserPhone: new FormControl({value:' ',disabled:true})
this makes the phone numbers of user to be non editable.
You can delete the data from array
this.data.splice(index, 1);
I know this question was long ago but I found no proper explanation and solution, so hopefully, my answer is useful :)
Assuming you install Docker Toolbox on Windows, both docker
and docker-machine
commands will be available. Often, people get confused when to use either of these.
The docker
commands are used only within a virtual machine to manage images. The docker-machine
commands are used on the host to manage the Linux VMs.
So, please use docker-machine
commands on your Windows machine. Use docker
command inside your VM. To use the docker
commands, for example, docker ps
, you either can open Docker Quickstart Terminal or run these on your cmd/bash/PowerShell:
docker-machine run default
/assuming default is your Linux VM/
docker-machine ssh default
This will start boot2docker and you will see the docker icon on the command line. Then you can use docker
commands.
Good luck :)
Relative paths are relative to current working directory. If you do not your want your path to be, it must be absolute.
But there is an often used trick to build an absolute path from current script: use its __file__
special attribute:
from pathlib import Path
path = Path(__file__).parent / "../data/test.csv"
with path.open() as f:
test = list(csv.reader(f))
This requires python 3.4+ (for the pathlib module).
If you still need to support older versions, you can get the same result with:
import csv
import os.path
my_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(my_path, "../data/test.csv")
with open(path) as f:
test = list(csv.reader(f))
[2020 edit: python3.4+ should now be the norm, so I moved the pathlib version inspired by jpyams' comment first]
To go one step further, I assume you want to do something with these dtypes.
df.dtypes.to_dict()
comes in handy.
my_type = 'float64' #<---
dtypes = dataframe.dtypes.to_dict()
for col_nam, typ in dtypes.items():
if (typ != my_type): #<---
raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")
You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype
will succeed when .dtype==np.float64
.
If you know the type will never be null
or undefined
, you should declare it as foo: Bar
without the ?
. Declaring a type with the ? Bar
syntax means it could potentially be undefined, which is something you need to check for.
In other words, the compiler is doing exactly what you're asking it to. If you want it to be optional, you'll need to the check later.
This worked for me :
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
@Column(name="end_date", nullable = false)
@DateTimeFormat(iso = ISO.DATE_TIME)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private LocalDateTime endDate;
Adding a space before the EOF delimiter allows to avoid cmd:
- shell: |
cat <<' EOF'
This is a test.
EOF
There are more than that. The executed executables are different.
npm run start
will run your projects local executable which is located in your node_modules/.bin.
ng serve
will run another executable which is global.
It means if you clone and install an Angular project which is created with angular-cli version 5 and your global cli version is 7, then you may have problems with ng build.
In my case, I was looking for a solution that allows one of the navbar items to be right aligned. In order to do this, you must add style="width:100%;"
to the <ul class="navbar-nav">
and then add the ml-auto
class to your navbar item.
TL:DR; return promises from you actions only when necessary, but DRY chaining the same actions.
For a long time I also though that returning actions contradicts the Vuex cycle of uni-directional data flow.
But, there are EDGE CASES where returning a promise from your actions might be "necessary".
Imagine a situation where an action can be triggered from 2 different components, and each handles the failure case differently. In that case, one would need to pass the caller component as a parameter to set different flags in the store.
Dumb example
Page where the user can edit the username in navbar and in /profile page (which contains the navbar). Both trigger an action "change username", which is asynchronous. If the promise fails, the page should only display an error in the component the user was trying to change the username from.
Of course it is a dumb example, but I don't see a way to solve this issue without duplicating code and making the same call in 2 different actions.
Just to add to @Anshul Singh Suryan's answer:
When we split the dataframe to just get the last column:
If we split like:
y = df.iloc[:,-1:] - y
remains a dataframe
However, if we split like
y = df.iloc[:,-1] - y
becomes a Series
.
This is a notable difference that I've found in the two approaches. If you don't care about the resultant type, you can use either of the two. Otherwise you need to take care of the above findings.
This is applicable for any number of rows you want to extract and not just the last row.
For example, if you want last n
number of rows of a dataframe, where n is any integer less than or equal to the number of columns present in the dataframe, then you can easily do the following:
y = df.iloc[:,n:]
Replace n
by the number of columns you want. Same is true for rows as well.
After having it defined in your manifest file, a friendlier alternative to the native solution would be using Aaper: https://github.com/LikeTheSalad/aaper like so:
@EnsurePermissions(permissions = [Manifest.permission.ACCESS_FINE_LOCATION])
private fun scanForLocation() {
// Your code that needs the location permission granted.
}
Disclaimer, I'm the creator of Aaper.
.NET Framework and .NET Core are both frameworks.
.NET Standard is a standard (in other words, a specification).
You can make an executable project (like a console application, or ASP.NET application) with .NET Framework and .NET Core, but not with .NET Standard.
With .NET Standard you can make only a class library project that cannot be executed standalone and should be referenced by another .NET Core or .NET Framework executable project.
Regex is not on the list of search features, and it was on (more or less, as Better message search functionality (i.e. Wildcard and partial word search)) the list of pre-canned feature requests, so the answer is "you cannot do this via the Gmail web UI" :-(
There are no current Labs features which offer this. SIEVE filters would be another way to do this, that too was not supported, there seems to no longer be any definitive statement on SIEVE support in the Gmail help.
Updated for link rot The pre-canned list of feature requests was, er canned, the original is on archive.org dated 2012, now you just get redirected to a dumbed down page telling you how to give feedback. Lack of SIEVE support was covered in answer 78761 Does Gmail support all IMAP features?, since some time in 2015 that answer silently redirects to the answer about IMAP client configuration, archive.org has a copy dated 2014.
With the current search facility brackets of any form () {} []
are used for grouping, they have no observable effect if there's just one term within. Using (aaa|bbb)
and [aaa|bbb]
are equivalent and will both find words aaa
or bbb
. Most other punctuation characters, including \
, are treated as a space or a word-separator, +
-
:
and "
do have special meaning though, see the help.
As of 2016, only the form "{term1 term2}
" is documented for this, and is equivalent to the search "term1 OR term2
".
You can do regex searches on your mailbox (within limits) programmatically via Google docs: http://www.labnol.org/internet/advanced-gmail-search/21623/ has source showing how it can be done (copy the document, then Tools > Script Editor
to get the complete source).
You could also do this via IMAP as described here: Python IMAP search for partial subject and script something to move messages to different folder. The IMAP SEARCH verb only supports substrings, not regex (Gmail search is further limited to complete words, not substrings), further processing of the matches to apply a regex would be needed.
For completeness, one last workaround is: Gmail supports plus addressing, if you can change the destination address to [email protected]
it will still be sent to your mailbox where you can filter by recipient address. Make sure to filter using the full email address to:[email protected]
. This is of course more or less the same thing as setting up a dedicated Gmail address for this purpose :-)
This class was compiled with a JDK more recent than the one used for execution.
The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.
Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).
You just wrap your query in another one:
SELECT COUNT(*), SUM(Age)
FROM (
SELECT availables.bookdate AS Count, DATEDIFF(now(),availables.updated_at) as Age
FROM availables
INNER JOIN rooms
ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate
) AS tmp;
This problem occures when you use your service via other application.If application has config file just add your service config information to this file. In my situation there wasn't any config file so I use this technique and it worked fine.Just store url address in application,read it and using BasicHttpBinding() method send it to service application as parameter.This is simple demonstration how I did it:
Configuration config = new Configuration(dataRowSet[0]["ServiceUrl"].ToString());
var remoteAddress = new System.ServiceModel.EndpointAddress(config.Url);
SimpleService.PayPointSoapClient client =
new SimpleService.PayPointSoapClient(new System.ServiceModel.BasicHttpBinding(),
remoteAddress);
SimpleService.AccountcredResponse response = client.AccountCred(request);
First you need to separate your class from the further extensions ex you cannot extend AddAddressComponent.defaultProps
within the class
instead move it outside.
I will also recommend you to read about the Constructor and React's lifecycle: see Component Specs and Lifecycle
Here is what you want:
import PropTypes from 'prop-types';
class AddAddressComponent extends React.Component {
render() {
let { provinceList, cityList } = this.props;
if(cityList === undefined || provinceList === undefined){
console.log('undefined props');
}
}
}
AddAddressComponent.contextTypes = {
router: PropTypes.object.isRequired
};
AddAddressComponent.defaultProps = {
cityList: [],
provinceList: [],
};
AddAddressComponent.propTypes = {
userInfo: PropTypes.object,
cityList: PropTypes.array.isRequired,
provinceList: PropTypes.array.isRequired,
}
export default AddAddressComponent;
If you want nice validation popups and images when an error occurs you can use the setError
method of the EditText
class as I describe here
QT is able to pull that of (thanks to the meta object compiler):
QNetworkReply::NetworkError error;
error = fetchStuff();
if (error != QNetworkReply::NoError) {
QString errorValue;
QMetaObject meta = QNetworkReply::staticMetaObject;
for (int i=0; i < meta.enumeratorCount(); ++i) {
QMetaEnum m = meta.enumerator(i);
if (m.name() == QLatin1String("NetworkError")) {
errorValue = QLatin1String(m.valueToKey(error));
break;
}
}
QMessageBox box(QMessageBox::Information, "Failed to fetch",
"Fetching stuff failed with error '%1`").arg(errorValue),
QMessageBox::Ok);
box.exec();
return 1;
}
In Qt every class that has the Q_OBJECT macro will automatically have a static member "staticMetaObject" of the type QMetaObject. You can then find all sorts of cool things like the properties, signals, slots and indeed enums.
There are a number of ways to go about this. One way would be to enter the date 8/1/2013
manually in the first cell (say A1
for example's sake) and then in B1
type the following formula (and then drag it across):
=DATE(YEAR(A1),MONTH(A1)+1,1)
Since you only want to see month and year, you can format accordingly using the different custom date formats available.
The format you're looking for is YY-Mmm
.
I wrote a post a few months back on how to set up user registration and login functionality with Angular, you can check it out at http://jasonwatmore.com/post/2015/03/10/AngularJS-User-Registration-and-Login-Example.aspx
I check if the user is logged in the $locationChangeStart
event, here is my main app.js showing this:
(function () {
'use strict';
angular
.module('app', ['ngRoute', 'ngCookies'])
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'home/home.view.html',
controllerAs: 'vm'
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'login/login.view.html',
controllerAs: 'vm'
})
.when('/register', {
controller: 'RegisterController',
templateUrl: 'register/register.view.html',
controllerAs: 'vm'
})
.otherwise({ redirectTo: '/login' });
}
run.$inject = ['$rootScope', '$location', '$cookieStore', '$http'];
function run($rootScope, $location, $cookieStore, $http) {
// keep user logged in after page refresh
$rootScope.globals = $cookieStore.get('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
}
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// redirect to login page if not logged in and trying to access a restricted page
var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
var loggedIn = $rootScope.globals.currentUser;
if (restrictedPage && !loggedIn) {
$location.path('/login');
}
});
}
})();
First Google hit says:
this is usually a mismatch in the client/server bindings, where the message version in the service uses SOAP 1.2 (which expects application/soap+xml) and the version in the client uses SOAP 1.1 (which sends text/xml). WSHttpBinding uses SOAP 1.2, BasicHttpBinding uses SOAP 1.1.
It usually seems to be a wsHttpBinding on one side and a basicHttpBinding on the other.
I find letter identifiers to be more readable and more indicative of parsed type:
1 - 7f / 10
1 - 7 / 10f
or:
1 - 7d / 10
1 - 7 / 10d
I'd avoid eval.
To solve this problem, you should know these things about JavaScript.
.
rather than square brackets []
, or vice versa.Your problem is a result of considering the dot manner of reference rather than the square bracket manner.
So, why not something like,
window["functionName"]();
That's assuming your function lives in the global space. If you've namespaced, then:
myNameSpace["functionName"]();
Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.
This can be done easily and cleanly with float
.
Demo: jsfiddle.net/KcdpW
HTML:
<ul>
<li>Item 1 <span class="right">(1)</span></li>
<li>Item 2 <span class="right">(2)</span></li>
</ul>?
CSS:
ul {
width: 10em
}
.right {
float: right
}?
This is how I solved it
Now rebuild, and it will install the latest JAR's in the correct location.
i think it always boils to the classpath
. having said that if you run from the same folder where your .class is then change Scanner input = new Scanner(new File("word.txt"));
to Scanner input = new Scanner(new File("./word.txt"));
that should work
import pickle
f=open("filename.dat","rb")
try:
while True:
x=pickle.load(f)
print x
except EOFError:
pass
f.close()
The source code for BufferedReader shows that the underlying is closed when you close the BufferedReader.
You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number 3
(and uses it as default), so switch back to a value of 2
which can be read by Python 2.
Check the protocol
parameter in pickle.dump
. Your resulting code will look like this.
pickle.dump(your_object, your_file, protocol=2)
There is no protocol
parameter in pickle.load
because pickle
can determine the protocol from the file.
sudo ln -sf /usr/lib/...."adapt-it"..../qt5/plugins/platforms/ /usr/bin/
It creates the symbolic link it's missed. Good for QT ! Good for VLC !!
Two important CSS properties to set for full height pages are these:
Allow the body to grow as high as the content in it requires.
html { height: 100%; }
Force the body not to get any smaller than then window height.
body { min-height: 100%; }
What you do with your gird is irrelevant as long as you use fractions or percentages you should be safe in all cases.
If you want to get values in Javascript on frontend, you can use the native way to do it by using :
document.getElementsByName("movie")[0].value;
Where "movie"
is the name of your input
<input type="text" name="movie">
If you want to get it on angular.js controller, you can use;
$scope.movie
Misko Hevery, from Google, has some interesting articles on exactly this topic...
Singletons are Pathological Liars has a unit testing example that illustrates how singletons can make it difficult to figure out dependency chains and start or test an application. It is a fairly extreme example of abuse, but the point that he makes is still valid:
Singletons are nothing more than global state. Global state makes it so your objects can secretly get hold of things which are not declared in their APIs, and, as a result, Singletons make your APIs into pathological liars.
Where have all the Singletons Gone makes the point that dependency injection has made it easy to get instances to constructors that require them, which alleviates the underlying need behind the bad, global Singletons decried in the first article.
You can get the next auto-increment value by doing:
SHOW TABLE STATUS FROM tablename LIKE Auto_increment
/*or*/
SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = 'tablename'
Note that you should not use this to alter the table, use an auto_increment column to do that automatically instead.
The problem is that last_insert_id()
is retrospective and can thus be guaranteed within the current connection.
This baby is prospective and is therefore not unique per connection and cannot be relied upon.
Only in a single connection database would it work, but single connection databases today have a habit of becoming multiple connection databases tomorrow.
See: SHOW TABLE STATUS
The above did not work for me but this did
<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>
With this, you can perform some code in the get
or set
scope.
private string _myProperty;
public string myProperty
{
get { return _myProperty; }
set { _myProperty = value; }
}
You also can use automatic properties:
public string myProperty
{
get;
set;
}
And .Net Framework will manage for you. It was create because it is a good pratice and make it easy to do.
You also can control the visibility of these scopes, for sample:
public string myProperty
{
get;
private set;
}
public string myProperty2
{
get;
protected set;
}
public string myProperty3
{
get;
}
Now in C# you can initialize the value of a property. For sample:
public int Property { get; set; } = 1;
If also can define it and make it readonly, without a set.
public int Property { get; } = 1;
And finally, you can define an arrow function.
public int Property => GetValue();
Here's what worked for me:
background-size: auto 100%;
you should add style="display:none"
in any of <tr>
that you want to hide.
var CommentData= "u_id=" + $(this).attr("u_id") + "&post_id=" + $(this).attr("p_id") + "&comment=" + $(this).val();
That's something controlled by your terminal, not by printf
.
printf
simply sends a \t
to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.
html body {
background: url(/assets/images/header-bg.jpg) no-repeat top center fixed;
width: 100%;
height: 100%;
min-width: 100%;
min-height: 100%;
-webkit-background-size: auto auto;
-moz-background-size: auto auto;
-o-background-size: auto auto;
background-size: auto auto;
}
As Andrew said, your text should be doing just that.
There is one instance that I can think of that will behave in the manner you suggest, and that is if you have the whitespace property set.
See if you don't have the following in your CSS somewhere:
white-space: nowrap
That will cause text to continue on the same line until interrupted by a line break.
OK, my apologies, not sure if edited or added the mark-up afterwards (didn't see it at first).
The overflow-x property is what's causing the scroll bar to appear. Remove that and the div will adjust to as high as it needs to be to contain all your text.
Why cant we just use eval()?
def install():
print "In install"
New method
def installWithOptions(var1, var2):
print "In install with options " + var1 + " " + var2
And then you call the method as below
method_name1 = 'install()'
method_name2 = 'installWithOptions("a","b")'
eval(method_name1)
eval(method_name2)
This gives the output as
In install
In install with options a b
I've used a few CSS hacks and targeted Chrome/Safari/Firefox/IE individually, as each browser renders selects a bit differently. I've tested on all browsers except IE.
For Safari/Chrome, set the height
and line-height
you want for your <select />
.
For Firefox, we're going to kill Firefox's default padding and border, then set our own. Set padding to whatever you like.
For IE 8+, just like Chrome, we've set the height
and line-height
properties. These two media queries
can be combined. But I kept it separate for demo purposes. So you can see what I'm doing.
Please note, for the height/line-height
property to work in Chrome/Safari OSX, you must set the background
to a custom value. I changed the color in my example.
Here's a jsFiddle of the below: http://jsfiddle.net/URgCB/4/
For the non-hack route, why not use a custom select plug-in via jQuery? Check out this: http://codepen.io/wallaceerick/pen/ctsCz
HTML:
<select>
<option>Here's one option</option>
<option>here's another option</option>
</select>
CSS:
@media screen and (-webkit-min-device-pixel-ratio:0) { /*safari and chrome*/
select {
height:30px;
line-height:30px;
background:#f4f4f4;
}
}
select::-moz-focus-inner { /*Remove button padding in FF*/
border: 0;
padding: 0;
}
@-moz-document url-prefix() { /* targets Firefox only */
select {
padding: 15px 0!important;
}
}
@media screen\0 { /* IE Hacks: targets IE 8, 9 and 10 */
select {
height:30px;
line-height:30px;
}
}
I have solved the issue using 2 answers:
Changing .htaccess it a bit as follows for statics:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]
If there are any other static files needed just add the extension to the previous declared list
is there a possibility that casting a double created via
Math.round()
will still result in a truncated down number
No, round()
will always round your double to the correct value, and then, it will be cast to an long
which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.
Here are the docs from Math.round(double)
:
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)
Use empty
(it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"
If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"
Update: as per the comments, the Map
turns out to actually be a List
(please work on your naming conventions). To check if a List
contains an item the "normal" EL way, use JSTL fn:contains
(although not explicitly documented, it works for List
as well).
styleClass="#{empty obj.validationErrorMap ? ' ' :
(fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"
ES6 - I am including an example, which was helpful for me:
In a "short if statement" you can pass empty function like this:
isReady ? ()=>{} : onClick
This seems to be the shortest approach.
()=>{}
It seems you need DataFrame.var
:
Normalized by N-1 by default. This can be changed using the ddof argument
var1 = credit_card.var()
Sample:
#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
var1 = credit_card.var()
print (var1)
A 8.8
B 10.0
C 10.0
D 7.7
E 7.8
dtype: float64
var2 = credit_card.var(axis=1)
print (var2)
0 4.3
1 3.8
2 9.8
3 12.2
4 2.3
dtype: float64
If need numpy solutions with numpy.var
:
print (np.var(credit_card.values, axis=0))
[ 7.04 8. 8. 6.16 6.24]
print (np.var(credit_card.values, axis=1))
[ 3.44 3.04 7.84 9.76 1.84]
Differences are because by default ddof=1
in pandas
, but you can change it to 0
:
var1 = credit_card.var(ddof=0)
print (var1)
A 7.04
B 8.00
C 8.00
D 6.16
E 6.24
dtype: float64
var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0 3.44
1 3.04
2 7.84
3 9.76
4 1.84
dtype: float64
You can't search LONGs directly. LONGs can't appear in the WHERE clause. They can appear in the SELECT list though so you can use that to narrow down the number of rows you'd have to examine.
Oracle has recommended converting LONGs to CLOBs for at least the past 2 releases. There are fewer restrictions on CLOBs.
.aspx
uses a full lifecycle (Init
, Load
, PreRender
) and can respond to button clicks etc.
An .ashx
has just a single ProcessRequest
method.
This question has been already beaten to death, but I'll share this anyway in case someone else out there is struggling with the horrible mess that is AngularJS scopes. This will cover =
, <
, @
, &
and ::
. The full write up can be found here.
=
establishes a two way binding. Changing the property in the parent will result in change in the child, and vice versa.
<
establishes a one way binding, parent to child. Changing the property in the parent will result in change in the child, but changing the child property will not affect the parent property.
@
will assign to the child property the string value of the tag attribute. If the attribute contains an expression, the child property updates whenever the expression evaluates to a different string. For example:
<child-component description="The movie title is {{$ctrl.movie.title}}" />
bindings: {
description: '@',
}
Here, the description
property in the child scope will be the current value of the expression "The movie title is {{$ctrl.movie.title}}"
, where movie
is an object in the parent scope.
&
is a bit tricky, and in fact there seems to be no compelling reason to ever use it. It allows you to evaluate an expression in the parent scope, substituting parameters with variables from the child scope. An example (plunk):
<child-component
foo = "myVar + $ctrl.parentVar + myOtherVar"
</child-component>
angular.module('heroApp').component('childComponent', {
template: "<div>{{ $ctrl.parentFoo({myVar:5, myOtherVar:'xyz'}) }}</div>",
bindings: {
parentFoo: '&foo'
}
});
Given parentVar=10
, the expression parentFoo({myVar:5, myOtherVar:'xyz'})
will evaluate to 5 + 10 + 'xyz'
and the component will render as:
<div>15xyz</div>
When would you ever want to use this convoluted functionality? &
is often used by people to pass to the child scope a callback function in the parent scope. In reality, however, the same effect can be achieved by using '<' to pass the function, which is more straightforward and avoids the awkward curly braces syntax to pass parameters ({myVar:5, myOtherVar:'xyz'}
). Consider:
Callback using &
:
<child-component parent-foo="$ctrl.foo(bar)"/>
angular.module('heroApp').component('childComponent', {
template: '<button ng-click="$ctrl.parentFoo({bar:'xyz'})">Call foo in parent</button>',
bindings: {
parentFoo: '&'
}
});
Callback using <
:
<child-component parent-foo="$ctrl.foo"/>
angular.module('heroApp').component('childComponent', {
template: '<button ng-click="$ctrl.parentFoo('xyz')">Call foo in parent</button>',
bindings: {
parentFoo: '<'
}
});
Note that objects (and arrays) are passed by reference to the child scope, not copied. What this means is that even if it's a one-way binding, you are working with the same object in both the parent and the child scope.
To see the different prefixes in action, open this plunk.
One-time binding(initialization) using::
[Official docs]
Later versions of AngularJS introduce the option to have a one-time binding, where the child scope property is updated only once. This improves performance by eliminating the need to watch the parent property. The syntax is different from above; to declare a one-time binding, you add ::
in front of the expression in the component tag:
<child-component
tagline = "::$ctrl.tagline">
</child-component>
This will propagate the value of tagline
to the child scope without establishing a one-way or two-way binding. Note: if tagline
is initially undefined
in the parent scope, angular will watch it until it changes and then make a one-time update of the corresponding property in the child scope.
The table below shows how the prefixes work depending on whether the property is an object, array, string, etc.
PROCESS="process name shown in ps -ef"
START_OR_STOP=1 # 0 = start | 1 = stop
MAX=30
COUNT=0
until [ $COUNT -gt $MAX ] ; do
echo -ne "."
PROCESS_NUM=$(ps -ef | grep "$PROCESS" | grep -v `basename $0` | grep -v "grep" | wc -l)
if [ $PROCESS_NUM -gt 0 ]; then
#runs
RET=1
else
#stopped
RET=0
fi
if [ $RET -eq $START_OR_STOP ]; then
sleep 5 #wait...
else
if [ $START_OR_STOP -eq 1 ]; then
echo -ne " stopped"
else
echo -ne " started"
fi
echo
exit 0
fi
let COUNT=COUNT+1
done
if [ $START_OR_STOP -eq 1 ]; then
echo -ne " !!$PROCESS failed to stop!! "
else
echo -ne " !!$PROCESS failed to start!! "
fi
echo
exit 1
Bootstrap 3 with DataTables Example: Bootstrap Docs & DataTables Docs
$(document).ready(function() {
$('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap.min.css rel=stylesheet><div class=container><h1>Bootstrap 3 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap.min.js></script>
_x000D_
Bootstrap 4 with DataTables Example: Bootstrap Docs & DataTables Docs
$(document).ready(function() {
$('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap4.min.css rel=stylesheet><div class=container><h1>Bootstrap 4 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-inverse table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tfoot><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>61<td>2011/04/25<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>63<td>2011/07/25<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>66<td>2009/01/12<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>22<td>2012/03/29<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>33<td>2008/11/28<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>61<td>2012/12/02<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>59<td>2012/08/06<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>55<td>2010/10/14<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>39<td>2009/09/15<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>23<td>2008/12/13<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>30<td>2008/12/19<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>22<td>2013/03/03<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>36<td>2008/10/16<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>43<td>2012/12/18<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>19<td>2010/03/17<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>66<td>2012/11/27<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>64<td>2010/06/09<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>59<td>2009/04/10<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>41<td>2012/10/13<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>35<td>2012/09/26<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>30<td>2011/09/03<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>40<td>2009/06/25<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>21<td>2011/12/12<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>23<td>2010/09/20<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>47<td>2009/10/09<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>42<td>2010/12/22<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>28<td>2010/11/14<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>28<td>2011/06/07<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>48<td>2010/03/11<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>20<td>2011/08/14<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>37<td>2011/06/02<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>53<td>2009/10/22<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>27<td>2011/05/07<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>22<td>2008/10/26<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>46<td>2011/03/09<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>47<td>2009/12/09<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>51<td>2008/12/16<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>41<td>2010/02/12<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>62<td>2009/02/14<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>37<td>2008/12/11<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>65<td>2008/09/26<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>64<td>2011/02/03<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>38<td>2011/05/03<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>37<td>2009/08/19<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>61<td>2013/08/11<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>47<td>2009/07/07<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>64<td>2012/04/09<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>63<td>2010/01/04<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>56<td>2012/06/01<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>43<td>2013/02/01<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>46<td>2011/12/06<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>47<td>2011/03/21<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>21<td>2009/02/27<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>30<td>2010/07/14<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>51<td>2008/11/13<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>29<td>2011/06/27<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>27<td>2011/01/25<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap4.min.js></script>
_x000D_
Bootstrap 3 with Bootstrap Table Example: Bootstrap Docs & Bootstrap Table Docs
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.css rel=stylesheet><table data-sort-name=stargazers_count data-sort-order=desc data-toggle=table data-url="https://api.github.com/users/wenzhixin/repos?type=owner&sort=full_name&direction=asc&per_page=100&page=1"><thead><tr><th data-field=name data-sortable=true>Name<th data-field=stargazers_count data-sortable=true>Stars<th data-field=forks_count data-sortable=true>Forks<th data-field=description data-sortable=true>Description</thead></table><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.js></script>
_x000D_
Bootstrap 3 with Bootstrap Sortable Example: Bootstrap Docs & Bootstrap Sortable Docs
function randomDate(t,e){return new Date(t.getTime()+Math.random()*(e.getTime()-t.getTime()))}function randomName(){return["Jack","Peter","Frank","Steven"][Math.floor(4*Math.random())]+" "+["White","Jackson","Sinatra","Spielberg"][Math.floor(4*Math.random())]}function newTableRow(){var t=moment(randomDate(new Date(2e3,0,1),new Date)).format("D.M.YYYY"),e=Math.round(Math.random()*Math.random()*100*100)/100,a=Math.round(Math.random()*Math.random()*100*100)/100,r=Math.round(Math.random()*Math.random()*100*100)/100;return"<tr><td>"+randomName()+"</td><td>"+e+"</td><td>"+a+"</td><td>"+r+"</td><td>"+Math.round(100*(e+a+r))/100+"</td><td data-dateformat='D-M-YYYY'>"+t+"</td></tr>"}function customSort(){alert("Custom sort.")}!function(t,e){"use strict";"function"==typeof define&&define.amd?define("tinysort",function(){return e}):t.tinysort=e}(this,function(){"use strict";function t(t,e){for(var a,r=t.length,o=r;o--;)e(t[a=r-o-1],a)}function e(t,e,a){for(var o in e)(a||t[o]===r)&&(t[o]=e[o]);return t}function a(t,e,a){u.push({prepare:t,sort:e,sortBy:a})}var r,o=!1,n=null,s=window,d=s.document,i=parseFloat,l=/(-?\d+\.?\d*)\s*$/g,c=/(\d+\.?\d*)\s*$/g,u=[],f=0,h=0,p=String.fromCharCode(4095),m={selector:n,order:"asc",attr:n,data:n,useVal:o,place:"org",returns:o,cases:o,natural:o,forceStrings:o,ignoreDashes:o,sortFunction:n,useFlex:o,emptyEnd:o};return s.Element&&function(t){t.matchesSelector=t.matchesSelector||t.mozMatchesSelector||t.msMatchesSelector||t.oMatchesSelector||t.webkitMatchesSelector||function(t){for(var e=this,a=(e.parentNode||e.document).querySelectorAll(t),r=-1;a[++r]&&a[r]!=e;);return!!a[r]}}(Element.prototype),e(a,{loop:t}),e(function(a,s){function v(t){var a=!!t.selector,r=a&&":"===t.selector[0],o=e(t||{},m);E.push(e({hasSelector:a,hasAttr:!(o.attr===n||""===o.attr),hasData:o.data!==n,hasFilter:r,sortReturnNumber:"asc"===o.order?1:-1},o))}function b(t,e,a){for(var r=a(t.toString()),o=a(e.toString()),n=0;r[n]&&o[n];n++)if(r[n]!==o[n]){var s=Number(r[n]),d=Number(o[n]);return s==r[n]&&d==o[n]?s-d:r[n]>o[n]?1:-1}return r.length-o.length}function g(t){for(var e,a,r=[],o=0,n=-1,s=0;e=(a=t.charAt(o++)).charCodeAt(0);){var d=46==e||e>=48&&57>=e;d!==s&&(r[++n]="",s=d),r[n]+=a}return r}function w(){return Y.forEach(function(t){F.appendChild(t.elm)}),F}function S(t){var e=t.elm,a=d.createElement("div");return t.ghost=a,e.parentNode.insertBefore(a,e),t}function y(t,e){var a=t.ghost,r=a.parentNode;r.insertBefore(e,a),r.removeChild(a),delete t.ghost}function C(t,e){var a,r=t.elm;return e.selector&&(e.hasFilter?r.matchesSelector(e.selector)||(r=n):r=r.querySelector(e.selector)),e.hasAttr?a=r.getAttribute(e.attr):e.useVal?a=r.value||r.getAttribute("value"):e.hasData?a=r.getAttribute("data-"+e.data):r&&(a=r.textContent),M(a)&&(e.cases||(a=a.toLowerCase()),a=a.replace(/\s+/g," ")),null===a&&(a=p),a}function M(t){return"string"==typeof t}M(a)&&(a=d.querySelectorAll(a)),0===a.length&&console.warn("No elements to sort");var x,N,F=d.createDocumentFragment(),D=[],Y=[],$=[],E=[],k=!0,A=a.length&&a[0].parentNode,T=A.rootNode!==document,R=a.length&&(s===r||!1!==s.useFlex)&&!T&&-1!==getComputedStyle(A,null).display.indexOf("flex");return function(){0===arguments.length?v({}):t(arguments,function(t){v(M(t)?{selector:t}:t)}),f=E.length}.apply(n,Array.prototype.slice.call(arguments,1)),t(a,function(t,e){N?N!==t.parentNode&&(k=!1):N=t.parentNode;var a=E[0],r=a.hasFilter,o=a.selector,n=!o||r&&t.matchesSelector(o)||o&&t.querySelector(o)?Y:$,s={elm:t,pos:e,posn:n.length};D.push(s),n.push(s)}),x=Y.slice(0),Y.sort(function(e,a){var n=0;for(0!==h&&(h=0);0===n&&f>h;){var s=E[h],d=s.ignoreDashes?c:l;if(t(u,function(t){var e=t.prepare;e&&e(s)}),s.sortFunction)n=s.sortFunction(e,a);else if("rand"==s.order)n=Math.random()<.5?1:-1;else{var p=o,m=C(e,s),v=C(a,s),w=""===m||m===r,S=""===v||v===r;if(m===v)n=0;else if(s.emptyEnd&&(w||S))n=w&&S?0:w?1:-1;else{if(!s.forceStrings){var y=M(m)?m&&m.match(d):o,x=M(v)?v&&v.match(d):o;y&&x&&m.substr(0,m.length-y[0].length)==v.substr(0,v.length-x[0].length)&&(p=!o,m=i(y[0]),v=i(x[0]))}n=m===r||v===r?0:s.natural&&(isNaN(m)||isNaN(v))?b(m,v,g):v>m?-1:m>v?1:0}}t(u,function(t){var e=t.sort;e&&(n=e(s,p,m,v,n))}),0==(n*=s.sortReturnNumber)&&h++}return 0===n&&(n=e.pos>a.pos?1:-1),n}),function(){var t=Y.length===D.length;if(k&&t)R?Y.forEach(function(t,e){t.elm.style.order=e}):N?N.appendChild(w()):console.warn("parentNode has been removed");else{var e=E[0].place,a="start"===e,r="end"===e,o="first"===e,n="last"===e;if("org"===e)Y.forEach(S),Y.forEach(function(t,e){y(x[e],t.elm)});else if(a||r){var s=x[a?0:x.length-1],d=s&&s.elm.parentNode,i=d&&(a&&d.firstChild||d.lastChild);i&&(i!==s.elm&&(s={elm:i}),S(s),r&&d.appendChild(s.ghost),y(s,w()))}else(o||n)&&y(S(x[o?0:x.length-1]),w())}}(),Y.map(function(t){return t.elm})},{plugin:a,defaults:m})}()),function(t,e){"function"==typeof define&&define.amd?define(["jquery","tinysort","moment"],e):e(t.jQuery,t.tinysort,t.moment||void 0)}(this,function(t,e,a){var r,o,n,s=t(document);function d(e){var s=void 0!==a;r=e.sign?e.sign:"arrow","default"==e.customSort&&(e.customSort=c),o=e.customSort||o||c,n=e.emptyEnd,t("table.sortable").each(function(){var r=t(this),o=!0===e.applyLast;r.find("span.sign").remove(),r.find("> thead [colspan]").each(function(){for(var e=parseFloat(t(this).attr("colspan")),a=1;a<e;a++)t(this).after('<th class="colspan-compensate">')}),r.find("> thead [rowspan]").each(function(){for(var e=t(this),a=parseFloat(e.attr("rowspan")),r=1;r<a;r++){var o=e.parent("tr"),n=o.next("tr"),s=o.children().index(e);n.children().eq(s).before('<th class="rowspan-compensate">')}}),r.find("> thead tr").each(function(e){t(this).find("th").each(function(a){var r=t(this);r.addClass("nosort").removeClass("up down"),r.attr("data-sortcolumn",a),r.attr("data-sortkey",a+"-"+e)})}),r.find("> thead .rowspan-compensate, .colspan-compensate").remove(),r.find("th").each(function(){var e=t(this);if(void 0!==e.attr("data-dateformat")&&s){var o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var r=t(this);r.attr("data-value",a(r.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss"))})}else if(void 0!==e.attr("data-valueprovider")){o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var a=t(this);a.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(a.text())[0])})}}),r.find("td").each(function(){var e=t(this);void 0!==e.attr("data-dateformat")&&s?e.attr("data-value",a(e.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss")):void 0!==e.attr("data-valueprovider")?e.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(e.text())[0]):void 0===e.attr("data-value")&&e.attr("data-value",e.text())});var n=l(r),d=n.bsSort;r.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var a=t(this),r=a.closest("table.sortable");a.data("sortTable",r);var s=a.attr("data-sortkey"),i=o?n.lastSort:-1;d[s]=o?d[s]:a.attr("data-defaultsort"),void 0!==d[s]&&o===(s===i)&&(d[s]="asc"===d[s]?"desc":"asc",u(a,r))})})}function i(e){var a=t(e),r=a.data("sortTable")||a.closest("table.sortable");u(a,r)}function l(e){var a=e.data("bootstrap-sortable-context");return void 0===a&&(a={bsSort:[],lastSort:void 0},e.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var r=t(this),o=r.attr("data-sortkey");a.bsSort[o]=r.attr("data-defaultsort"),void 0!==a.bsSort[o]&&(a.lastSort=o)}),e.data("bootstrap-sortable-context",a)),a}function c(t,a){e(t,a)}function u(e,a){a.trigger("before-sort");var s=parseFloat(e.attr("data-sortcolumn")),d=l(a),i=d.bsSort;if(e.attr("colspan")){var c=parseFloat(e.data("mainsort"))||0,f=parseFloat(e.data("sortkey").split("-").pop());if(a.find("> thead tr").length-1>f)return void u(a.find('[data-sortkey="'+(s+c)+"-"+(f+1)+'"]'),a);s+=c}var h=e.attr("data-defaultsign")||r;if(a.find("> thead th").each(function(){t(this).removeClass("up").removeClass("down").addClass("nosort")}),t.browser.mozilla){var p=a.find("> thead div.mozilla");void 0!==p&&(p.find(".sign").remove(),p.parent().html(p.html())),e.wrapInner('<div class="mozilla"></div>'),e.children().eq(0).append('<span class="sign '+h+'"></span>')}else a.find("> thead span.sign").remove(),e.append('<span class="sign '+h+'"></span>');var m=e.attr("data-sortkey"),v="desc"!==e.attr("data-firstsort")?"desc":"asc",b=i[m]||v;d.lastSort!==m&&void 0!==i[m]||(b="asc"===b?"desc":"asc"),i[m]=b,d.lastSort=m,"desc"===i[m]?(e.find("span.sign").addClass("up"),e.addClass("up").removeClass("down nosort")):e.addClass("down").removeClass("up nosort");var g=a.children("tbody").children("tr"),w=[];t(g.filter('[data-disablesort="true"]').get().reverse()).each(function(e,a){var r=t(a);w.push({index:g.index(r),row:r}),r.remove()});var S=g.not('[data-disablesort="true"]');if(0!=S.length){var y="asc"===i[m]&&n;o(S,{emptyEnd:y,selector:"td:nth-child("+(s+1)+")",order:i[m],data:"value"})}t(w.reverse()).each(function(t,e){0===e.index?a.children("tbody").prepend(e.row):a.children("tbody").children("tr").eq(e.index-1).after(e.row)}),a.find("> tbody > tr > td.sorted,> thead th.sorted").removeClass("sorted"),S.find("td:eq("+s+")").addClass("sorted"),e.addClass("sorted"),a.trigger("sorted")}if(t.bootstrapSortable=function(t){null==t?d({}):t.constructor===Boolean?d({applyLast:t}):void 0!==t.sortingHeader?i(t.sortingHeader):d(t)},s.on("click",'table.sortable>thead th[data-defaultsort!="disabled"]',function(t){i(this)}),!t.browser){t.browser={chrome:!1,mozilla:!1,opera:!1,msie:!1,safari:!1};var f=navigator.userAgent;t.each(t.browser,function(e){t.browser[e]=!!new RegExp(e,"i").test(f),t.browser.mozilla&&"mozilla"===e&&(t.browser.mozilla=!!new RegExp("firefox","i").test(f)),t.browser.chrome&&"safari"===e&&(t.browser.safari=!1)})}t(t.bootstrapSortable)}),function(){var t=$("table");t.append(newTableRow()),t.append(newTableRow()),$("button.add-row").on("click",function(){var e=$(this);t.append(newTableRow()),e.data("sort")?$.bootstrapSortable(!0):$.bootstrapSortable(!1)}),$("button.change-sort").on("click",function(){$(this).data("custom")?$.bootstrapSortable(!0,void 0,customSort):$.bootstrapSortable(!0,void 0,"default")}),t.on("sorted",function(){alert("Table was sorted.")}),$("#event").on("change",function(){$(this).is(":checked")?t.on("sorted",function(){alert("Table was sorted.")}):t.off("sorted")}),$("input[name=sign]:radio").change(function(){$.bootstrapSortable(!0,$(this).val())})}();
_x000D_
table.sortable span.sign { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th:after { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th.arrow:after { content: ''; } table.sortable span.arrow, span.reversed, th.arrow.down:after, th.reversedarrow.down:after, th.arrow.up:after, th.reversedarrow.up:after { border-style: solid; border-width: 5px; font-size: 0; border-color: #ccc transparent transparent transparent; line-height: 0; height: 0; width: 0; margin-top: -2px; } table.sortable span.arrow.up, th.arrow.up:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed, th.reversedarrow.down:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed.up, th.reversedarrow.up:after { border-color: #ccc transparent transparent transparent; margin-top: -2px; } table.sortable span.az:before, th.az.down:after { content: "a .. z"; } table.sortable span.az.up:before, th.az.up:after { content: "z .. a"; } table.sortable th.az.nosort:after, th.AZ.nosort:after, th._19.nosort:after, th.month.nosort:after { content: ".."; } table.sortable span.AZ:before, th.AZ.down:after { content: "A .. Z"; } table.sortable span.AZ.up:before, th.AZ.up:after { content: "Z .. A"; } table.sortable span._19:before, th._19.down:after { content: "1 .. 9"; } table.sortable span._19.up:before, th._19.up:after { content: "9 .. 1"; } table.sortable span.month:before, th.month.down:after { content: "jan .. dec"; } table.sortable span.month.up:before, th.month.up:after { content: "dec .. jan"; } table.sortable thead th:not([data-defaultsort=disabled]) { cursor: pointer; position: relative; top: 0; left: 0; } table.sortable thead th:hover:not([data-defaultsort=disabled]) { background: #efefef; } table.sortable thead th div.mozilla { position: relative; }
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css rel=stylesheet><link href=https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><div class=container><div class=hero-unit><h1>Bootstrap Sortable</h1></div><table class="sortable table table-bordered table-striped"><thead><tr><th style=width:20%;vertical-align:middle data-defaultsign=nospan class=az data-defaultsort=asc rowspan=2><i class="fa fa-fw fa-map-marker"></i>Name<th style=text-align:center colspan=4 data-mainsort=3>Results<th data-defaultsort=disabled><tr><th style=width:20% colspan=2 data-mainsort=1 data-firstsort=desc>Round 1<th style=width:20%>Round 2<th style=width:20%>Total<t
You can read a very good solution in: http://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus
The best solution is on the "comments and discussions", see the "No need for static Create methods".
From this idea, I've done a factory. Note that I'm using Qt, but you can change QMap and QString for std equivalents.
#ifndef FACTORY_H
#define FACTORY_H
#include <QMap>
#include <QString>
template <typename T>
class Factory
{
public:
template <typename TDerived>
void registerType(QString name)
{
static_assert(std::is_base_of<T, TDerived>::value, "Factory::registerType doesn't accept this type because doesn't derive from base class");
_createFuncs[name] = &createFunc<TDerived>;
}
T* create(QString name) {
typename QMap<QString,PCreateFunc>::const_iterator it = _createFuncs.find(name);
if (it != _createFuncs.end()) {
return it.value()();
}
return nullptr;
}
private:
template <typename TDerived>
static T* createFunc()
{
return new TDerived();
}
typedef T* (*PCreateFunc)();
QMap<QString,PCreateFunc> _createFuncs;
};
#endif // FACTORY_H
Sample usage:
Factory<BaseClass> f;
f.registerType<Descendant1>("Descendant1");
f.registerType<Descendant2>("Descendant2");
Descendant1* d1 = static_cast<Descendant1*>(f.create("Descendant1"));
Descendant2* d2 = static_cast<Descendant2*>(f.create("Descendant2"));
BaseClass *b1 = f.create("Descendant1");
BaseClass *b2 = f.create("Descendant2");
Another approach (no plugin needed) is to just use .ctrlKey
property of the event object that gets passed in. It indicates if Ctrl was pressed at the time of the event, like this:
$(document).keypress("c",function(e) {
if(e.ctrlKey)
alert("Ctrl+C was pressed!!");
});
svn merge -r 854:853 l3toks.dtx
or
svn merge -c -854 l3toks.dtx
The two commands are equivalent.
If you are building the array once and want to find the maximum just once, iterating is the best you can do.
When you want to modify the array and occasionally want to know the maximum element, you should use a Priority Queue. One of the best data structures for that is a Fibonacci Heap, if this is too complicated use a Binary Heap which is slower but still good.
To find minimum and maximum, just build two heaps and change the sign of the numbers in one of them.
I was having the same problem while developing my own website. While it was resident locally, resources opened as file//
. For pages from the internet, including my own loaded as http://
, the F12 Developer did use Edge as default, but not while they were loaded into IE11 from local files.
After following the suggestions above, I unchecked the box for "Display intranet Sites in Compatibility View".
That did the trick without adding any extra coding to my web page, or adding a multitude of pages to populate the list. Now all local files open in Edge document mode with F12.
So if you are referring to using F12 for locally hosted files, this may help.
Firstly create a class Instance and call the non-static method using that instance. e.g,
class demo {
public static void main(String args[]) {
demo d = new demo();
d.add(10,20); // to call the non-static method
}
public void add(int x ,int y) {
int a = x;
int b = y;
int c = a + b;
System.out.println("addition" + c);
}
}
It is varchar
and not var_char
CREATE DATABASE IF NOT EXISTS courses;
USE courses;
CREATE TABLE IF NOT EXISTS teachers(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
addr VARCHAR(255) NOT NULL,
phone INT NOT NULL
);
You should use a SQL tool to visualize possbile errors like MySQL Workbench.
An additional simple solution
HTML:
<div id="d1">
<div id="d2">
Text
</div>
</div>
CSS:
#d1{
position:absolute;
top:100px;left:100px;
}
#d2{
border:1px solid black;
height:50px; width:50px;
display:table-cell;
vertical-align:middle;
text-align:center;
}
$.validator.addMethod("mymail", function(value, element) {
return this.optional( element ) || /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test( value );
}, "Enter valid email!");
This may help! a small modification to the answer by user4974898!
Use asymptote instead!
This is what it can look like:
https://asymptote.sourceforge.io/gallery/3Dgraphs/helix.html
This is the code: https://asymptote.sourceforge.io/gallery/3Dgraphs/helix.asy
Asymptote can also read in data files.
And the full gallery: https://asymptote.sourceforge.io/gallery/index.html
To use asymptote from within Python:
https://ctan.org/tex-archive/graphics/asymptote/base/asymptote.py
There might be a semicolon or bracket missing a line before your pasted line.
It seems fine to me; every string is allowed as an array index.
string str = "Error mEssage";
Response.Write("<script language=javascript>alert('"+str+"');</script>");
If you prefer named parameters, it's possible (with a few tricks) to actually pass named parameters to functions (also makes it possible to pass arrays and references).
The method I developed allows you to define named parameters passed to a function like this:
function example { args : string firstName , string lastName , integer age } {
echo "My name is ${firstName} ${lastName} and I am ${age} years old."
}
You can also annotate arguments as @required or @readonly, create ...rest arguments, create arrays from sequential arguments (using e.g. string[4]
) and optionally list the arguments in multiple lines:
function example {
args
: @required string firstName
: string lastName
: integer age
: string[] ...favoriteHobbies
echo "My name is ${firstName} ${lastName} and I am ${age} years old."
echo "My favorite hobbies include: ${favoriteHobbies[*]}"
}
In other words, not only you can call your parameters by their names (which makes up for a more readable core), you can actually pass arrays (and references to variables - this feature works only in Bash 4.3 though)! Plus, the mapped variables are all in the local scope, just as $1
(and others).
The code that makes this work is pretty light and works both in Bash 3 and Bash 4 (these are the only versions I've tested it with). If you're interested in more tricks like this that make developing with bash much nicer and easier, you can take a look at my Bash Infinity Framework, the code below is available as one of its functionalities.
shopt -s expand_aliases
function assignTrap {
local evalString
local -i paramIndex=${__paramIndex-0}
local initialCommand="${1-}"
if [[ "$initialCommand" != ":" ]]
then
echo "trap - DEBUG; eval \"${__previousTrap}\"; unset __previousTrap; unset __paramIndex;"
return
fi
while [[ "${1-}" == "," || "${1-}" == "${initialCommand}" ]] || [[ "${#@}" -gt 0 && "$paramIndex" -eq 0 ]]
do
shift # First colon ":" or next parameter's comma ","
paramIndex+=1
local -a decorators=()
while [[ "${1-}" == "@"* ]]
do
decorators+=( "$1" )
shift
done
local declaration=
local wrapLeft='"'
local wrapRight='"'
local nextType="$1"
local length=1
case ${nextType} in
string | boolean) declaration="local " ;;
integer) declaration="local -i" ;;
reference) declaration="local -n" ;;
arrayDeclaration) declaration="local -a"; wrapLeft= ; wrapRight= ;;
assocDeclaration) declaration="local -A"; wrapLeft= ; wrapRight= ;;
"string["*"]") declaration="local -a"; length="${nextType//[a-z\[\]]}" ;;
"integer["*"]") declaration="local -ai"; length="${nextType//[a-z\[\]]}" ;;
esac
if [[ "${declaration}" != "" ]]
then
shift
local nextName="$1"
for decorator in "${decorators[@]}"
do
case ${decorator} in
@readonly) declaration+="r" ;;
@required) evalString+="[[ ! -z \$${paramIndex} ]] || echo \"Parameter '$nextName' ($nextType) is marked as required by '${FUNCNAME[1]}' function.\"; " >&2 ;;
@global) declaration+="g" ;;
esac
done
local paramRange="$paramIndex"
if [[ -z "$length" ]]
then
# ...rest
paramRange="{@:$paramIndex}"
# trim leading ...
nextName="${nextName//\./}"
if [[ "${#@}" -gt 1 ]]
then
echo "Unexpected arguments after a rest array ($nextName) in '${FUNCNAME[1]}' function." >&2
fi
elif [[ "$length" -gt 1 ]]
then
paramRange="{@:$paramIndex:$length}"
paramIndex+=$((length - 1))
fi
evalString+="${declaration} ${nextName}=${wrapLeft}\$${paramRange}${wrapRight}; "
# Continue to the next parameter:
shift
fi
done
echo "${evalString} local -i __paramIndex=${paramIndex};"
}
alias args='local __previousTrap=$(trap -p DEBUG); trap "eval \"\$(assignTrap \$BASH_COMMAND)\";" DEBUG;'
In some cases, managed code can actually be faster than native code. For instance, "mark-and-sweep" garbage collection algorithms allow environments like the JRE or CLR to free large numbers of short-lived (usually) objects in a single pass, where most C/C++ heap objects are freed one-at-a-time.
From wikipedia:
For many practical purposes, allocation/deallocation-intensive algorithms implemented in garbage collected languages can actually be faster than their equivalents using manual heap allocation. A major reason for this is that the garbage collector allows the runtime system to amortize allocation and deallocation operations in a potentially advantageous fashion.
That said, I've written a lot of C# and a lot of C++, and I've run a lot of benchmarks. In my experience, C++ is a lot faster than C#, in two ways: (1) if you take some code that you've written in C#, port it to C++ the native code tends to be faster. How much faster? Well, it varies a whole lot, but it's not uncommon to see a 100% speed improvement. (2) In some cases, garbage collection can massively slow down a managed application. The .NET CLR does a terrible job with large heaps (say, > 2GB), and can end up spending a lot of time in GC--even in applications that have few--or even no--objects of intermediate life spans.
Of course, in most cases that I've encounted, managed languages are fast enough, by a long shot, and the maintenance and coding tradeoff for the extra performance of C++ is simply not a good one.
Here's some code that works for us. We found MSIE to be hit and miss with DomContentLoaded
, there appears to be some delay when no additional resources are cached (up to 300ms based on our console logging), and it triggers too fast when they are cached. So we resorted to a fallback for MISE. You also want to trigger the doStuff()
function whether DomContentLoaded
triggers before or after your external JS files.
// detect MSIE 9,10,11, but not Edge
ua=navigator.userAgent.toLowerCase();isIE=/msie/.test(ua);
function doStuff(){
//
}
if(isIE){
// play it safe, very few users, exec ur JS when all resources are loaded
window.onload=function(){doStuff();}
} else {
// add event listener to trigger your function when DOMContentLoaded
if(document.readyState==='loading'){
document.addEventListener('DOMContentLoaded',doStuff);
} else {
// DOMContentLoaded already loaded, so better trigger your function
doStuff();
}
}
I was getting the same error while opening the eclipse. to solve that I checked the log file inside the metadata folder. where I found that there is version mismatch of Java. so I have changed the VM inside my eclipse ini file.
-vm /opt/jdk1.8.0_191/jre/bin
Hope this will also help to solve your problem.
$(document).ready(function(){
$('#shares').val('');
});
You would expect that this is easily possible but that seems not be the case. The only way I see at the moment is to create a user defined JQL function. I never tried this but here is a plug-in:
http://confluence.atlassian.com/display/DEVNET/Plugin+Tutorial+-+Adding+a+JQL+Function+to+JIRA
References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.
EDIT::
I am thinking of
int &x = y;
as almost equivalent of
int* __px = &y;
#define x (*__px)
where __px
is a fresh name, and the #define x
works only inside the block containing the declaration of x
reference.
Using date()
and strtotime()
from the docs.
$date = "2012-01-05";
$year = date('Y', strtotime($date));
$month = date('F', strtotime($date));
echo $month
Take a look at java.text.DateFormat. Easier to use (with a bit less power) is the derived class, java.text.SimpleDateFormat
And here is a good intro to Java internationalization: http://java.sun.com/docs/books/tutorial/i18n/index.html (the "Formatting" section addressing your problem, and more).
All of these answers are simple and good. However, I always like to add an interactive mode to these scripts so that I can find false positives.
if [[ -n $inInteractiveMode ]]
then
echo -e -n "$oldFileName => $newFileName\nDo you want to do this change? [Y/n]: "
read run[[ -z $run || "$run" == "y" || "$run" == "Y" ]] && mv "$oldFileName" "$newFileName"
fi
Or make interactive mode the default and add a force flag (-f | --force) for automated scripts or if you're feeling daring. And this doesn't slow you down too much: the default response is "yes, I do want to rename" so you can just hit the enter key at each prompt (because of the ``-z $run\
test.
For Grammarly you can use:
<textarea data-gramm="false" />
Ok. I found a solution.
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h3 class="modal-title" id="modal-login-label">Capital Get It</h3>
<p>Log in:</p>
</div>
<div class="modal-body">
<h4>Youtube stuff</h4>
<iframe src="//www.youtube.com/embed/lAU0yCDKWb4" allowfullscreen="" frameborder="0" height="315" width="100%"></iframe>
</div>
</div>
</div>
</div>
</div>
for (int j = 0; j < 5; j++) //inner loop
should be replaced with
for (int j = 0; j < 5 && !exitloops; j++)
.
Here, in this case complete nested loops should be exit if condition is True
. But if we use exitloops
only to the upper loop
for (int i = 0; i < 5 && !exitloops; i++) //upper loop
Then inner loop will continues, because there is no extra flag that notify this inner loop to exit.
Example : if
i = 3
andj=2
then condition isfalse
. But in next iteration of inner loopj=3
then condition(i*j)
become9
which istrue
but inner loop will be continue tillj
become5
.
So, it must use exitloops
to the inner loops too.
boolean exitloops = false;
for (int i = 0; i < 5 && !exitloops; i++) { //here should exitloops as a Conditional Statement to get out from the loops if exitloops become true.
for (int j = 0; j < 5 && !exitloops; j++) { //here should also use exitloops as a Conditional Statement.
if (i * j > 6) {
exitloops = true;
System.out.println("Inner loop still Continues For i * j is => "+i*j);
break;
}
System.out.println(i*j);
}
}
In general it makes sense only to display the Whatsapp Link on iOS or Android Devices only, using java script:
if (navigator.userAgent.match(/iPhone|Android/i)) {
document.write('<a href="whatsapp://send?text=See..">Share on WhatApp</a>');
}
You cannot use var
in a field, only on local variables.
But even this won't work:
Site master = Master as Site;
Because you cannot use this
in a field and Master as Site
is the same as this.Master as Site
. So just initialize the field from Page_Init
when the page is fully initialized and you can use this
:
Site master = null;
protected void Page_Init(object sender, EventArgs e)
{
master = this.Master as Site;
}
Since 7-zip version 9.25 alpha there is a new -spf
switch that can be used to store the full file paths including drive letter to the archive.
7zG.exe a -spf c:\BAckup\backup.zip @c:\temp\tmpFileList.txt
should be working just fine now.
Bootstrap tabs are not responsive out of the box. Responsive, IMO, is a style change, changing functions is Adaptive. There are a few plugins to turn the Bootstrap 3 tabs into a Collapse component. The best and most updated one is : https://github.com/flatlogic/bootstrap-tabcollapse.
Here's one way of implementing it:
This turns the content into a collapse component:
Dependencies:
HTML -- same as question with class name addition:
<ul class="nav nav-tabs content-tabs" id="maincontent" role="tablist">
jQuery:
$(document).ready(function() {
// DEPENDENCY: https://github.com/flatlogic/bootstrap-tabcollapse
$('.content-tabs').tabCollapse();
// initialize tab function
$('.nav-tabs a').click(function(e) {
e.preventDefault();
$(this).tab('show');
});
});
CSS -- optional for fat fingers and active states:
.panel-heading {
padding: 0
}
.panel-heading a {
display: block;
padding: 20px 10px;
}
.panel-heading a.collapsed {
background: #fff
}
.panel-heading a {
background: #f7f7f7;
border-radius: 5px;
}
.panel-heading a:after {
content: '-'
}
.panel-heading a.collapsed:after {
content: '+'
}
.nav.nav-tabs li a,
.nav.nav-tabs li.active > a:hover,
.nav.nav-tabs li.active > a:active,
.nav.nav-tabs li.active > a:focus {
border-bottom-width: 0px;
outline: none;
}
.nav.nav-tabs li a {
padding-top: 20px;
padding-bottom: 20px;
}
.tab-pane {
background: #fff;
padding: 10px;
border: 1px solid #ddd;
margin-top: -1px;
}
If you can't know the progress you should not fake it by abusing a progress bar, instead just display some sort of busy icon like en.wikipedia.org/wiki/Throbber#Spinning_wheel Show it when starting the task and hide it when it's finished. That would make for a more "honest" GUI.
You can also use regular expressions (less readable though)
string regex = "^.{0,7}abc";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex);
string Value1 = "sssddabcgghh";
Console.WriteLine(reg.Match(Value1).Success);
You're just missing one critical step. You have to explicitly pass the return value in to the second function.
def main():
l = defineAList()
useTheList(l)
Alternatively:
def main():
useTheList(defineAList())
Or (though you shouldn't do this! It might seem nice at first, but globals just cause you grief in the long run.):
l = []
def defineAList():
global l
l.extend(['1','2','3'])
def main():
global l
defineAList()
useTheList(l)
The function returns a value, but it doesn't create the symbol in any sort of global namespace as your code assumes. You have to actually capture the return value in the calling scope and then use it for subsequent operations.
Like this:
Dim rng as Range
Set rng = ActiveCell.Resize(numRows, numCols)
then read the contents of that range to an array:
Dim arr As Variant
arr = rng.Value
'arr is now a two-dimensional array of size (numRows, numCols)
or, select the range (I don't think that's what you really want, but you ask for this in the question).
rng.Select
The following is a solution extracted from Expert C Programming: Deep Secrets, which is supposed to work on SVr4. It uses stty and ioctl.
#include <sys/filio.h>
int kbhit()
{
int i;
ioctl(0, FIONREAD, &i);
return i; /* return a count of chars available to read */
}
main()
{
int i = 0;
intc='';
system("stty raw -echo");
printf("enter 'q' to quit \n");
for (;c!='q';i++) {
if (kbhit()) {
c=getchar();
printf("\n got %c, on iteration %d",c, i);
}
}
system("stty cooked echo");
}
Ok, something odd is happening here. To make this work, do NOT need to make any configuration changes in /etc/mysql/my.cnf . All you need to do is to restart the current mysql service in terminal:
sudo service mysql restart
Then if I want to "recreate" the bug, I simply restart the apache service:
sudo service apache2 restart
Which can then be fixed again by entering the following command:
sudo service mysql restart
So, it appears that the apache2 is doing something to not allow this feature when it starts up (which is then reversed/corrected if restart the mysql service).
Valid in Debian based distributions.
service mysqld restart
service httpd restart
Valid in RedHat based distributions
I did it with transparent *.cur 1px to 1px, but it looks like small dot. :( I think it's the best cross-browser thing that I can do. CSS2.1 has no value 'none' for 'cursor' property - it was added in CSS3. Thats why it's workable not everywhere.
Book.where.any_of(Book.where(:author => 'Poe'), Book.where(:author => 'Hemingway')
Edit:
Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs
See the working example: http://jsfiddle.net/U6aKT/
<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>
I found this on another site not sure if it works or not.
Application.Wait Now + 1/(24*60*60.0*2)
the numerical value 1 = 1 day
1/24 is one hour
1/(24*60) is one minute
so 1/(24*60*60*2) is 1/2 second
You need to use a decimal point somewhere to force a floating point number
Not sure if this will work worth a shot for milliseconds
Application.Wait (Now + 0.000001)
Maybe is better you use:
User.objects.filter(username=admin_username).exists()
Implement your adapter Filterable:
public class vJournalAdapter extends ArrayAdapter<JournalModel> implements Filterable{
private ArrayList<JournalModel> items;
private Context mContext;
....
then create your Filter class:
private class JournalFilter extends Filter{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
List<JournalModel> allJournals = getAllJournals();
if(constraint == null || constraint.length() == 0){
result.values = allJournals;
result.count = allJournals.size();
}else{
ArrayList<JournalModel> filteredList = new ArrayList<JournalModel>();
for(JournalModel j: allJournals){
if(j.source.title.contains(constraint))
filteredList.add(j);
}
result.values = filteredList;
result.count = filteredList.size();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count == 0) {
notifyDataSetInvalidated();
} else {
items = (ArrayList<JournalModel>) results.values;
notifyDataSetChanged();
}
}
}
this way, your adapter is Filterable, you can pass filter item to adapter's filter and do the work. I hope this will be helpful.
I just thought I'd mention something here which I had to spent a long time experimenting with before I finally realised what was going on. This may be so obvious to everyone here that they haven't bothered mentioning it. But it would've helped me if they had, so on that principle...!
NB: I am using Jython specifically, v 2.7, so just possibly this may not apply to CPython...
NB2: the first two lines of my .py file here are:
# -*- coding: utf-8 -*-
from __future__ import print_function
The "%" (AKA "interpolation operator") string construction mechanism causes ADDITIONAL problems too... If the default encoding of the "environment" is ASCII and you try to do something like
print( "bonjour, %s" % "fréd" ) # Call this "print A"
You will have no difficulty running in Eclipse... In a Windows CLI (DOS window) you will find that the encoding is code page 850 (my Windows 7 OS) or something similar, which can handle European accented characters at least, so it'll work.
print( u"bonjour, %s" % "fréd" ) # Call this "print B"
will also work.
If, OTOH, you direct to a file from the CLI, the stdout encoding will be None, which will default to ASCII (on my OS anyway), which will not be able to handle either of the above prints... (dreaded encoding error).
So then you might think of redirecting your stdout by using
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
and try running in the CLI piping to a file... Very oddly, print A above will work... But print B above will throw the encoding error! The following will however work OK:
print( u"bonjour, " + "fréd" ) # Call this "print C"
The conclusion I have come to (provisionally) is that if a string which is specified to be a Unicode string using the "u" prefix is submitted to the %-handling mechanism it appears to involve the use of the default environment encoding, regardless of whether you have set stdout to redirect!
How people deal with this is a matter of choice. I would welcome a Unicode expert to say why this happens, whether I've got it wrong in some way, what the preferred solution to this, whether it also applies to CPython, whether it happens in Python 3, etc., etc.
ImageView iv= (ImageView)findViewById(R.id.img_selected_image);
public static int getDrawable(Context context, String name)//method to get id
{
Assert.assertNotNull(context);
Assert.assertNotNull(name);
return context.getResources().getIdentifier(name, //return id
"your drawable", context.getPackageName());
}
image.setImageResource(int Id);//set id using this method
To remove the variable from the current command session without removing it permanently, use the regular built-in set
command - just put nothing after the equals sign:
set FOOBAR=
To confirm, run set
with no arguments and check the current environment. The variable should be missing from the list entirely.
Note: this will only remove the variable from the current environment - it will not persist the change to the registry. When a new command process is started, the variable will be back.
For synchronizing threads I prefer using CountDownLatch
which helps threads to wait until the process being performed complete. In this case, the worker class is set up with a CountDownLatch
instance with a given count. A call to await
method will block until the current count reaches zero due to invocations of the countDown
method or the timeout set is reached. This approach allows interrupting a thread instantly without having to wait for the specified waiting time to elapse:
public class IndexProcessor implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
private final CountDownLatch countdownlatch;
public IndexProcessor(CountDownLatch countdownlatch) {
this.countdownlatch = countdownlatch;
}
public void run() {
try {
while (!countdownlatch.await(15000, TimeUnit.MILLISECONDS)) {
LOGGER.debug("Processing...");
}
} catch (InterruptedException e) {
LOGGER.error("Exception", e);
run = false;
}
}
}
When you want to finish execution of the other thread, execute countDown on the CountDownLatch
and join
the thread to the main thread:
public class SearchEngineContextListener implements ServletContextListener {
private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);
private Thread thread = null;
private IndexProcessor runnable = null;
private CountDownLatch countdownLatch = null;
@Override
public void contextInitialized(ServletContextEvent event) {
countdownLatch = new CountDownLatch(1);
Thread thread = new Thread(new IndexProcessor(countdownLatch));
LOGGER.debug("Starting thread: " + thread);
thread.start();
LOGGER.debug("Background process successfully started.");
}
@Override
public void contextDestroyed(ServletContextEvent event) {
LOGGER.debug("Stopping thread: " + thread);
if (countdownLatch != null)
{
countdownLatch.countDown();
}
if (thread != null) {
try {
thread.join();
} catch (InterruptedException e) {
LOGGER.error("Exception", e);
}
LOGGER.debug("Thread successfully stopped.");
}
}
}
Your interior <div>
elements should likely both be float:left
. Divs size to 100% the size of their container width automatically. Try using display:inline-block
instead of width:auto
on the container div. Or possibly float:left
the container and also apply overflow:auto
. Depends on what you're after exactly.
Use a CASE statement instead of IF.
To delete column use this,
ALTER TABLE `tbl_Country` DROP `your_col`
TortoiseSVN has a command-line interface that can be used for TortoiseSVN GUI automation and it's different from the normal Subversion one.
You can find information about the command-line options of TortoiseSVN in the documentation:
Appendix D. Automating TortoiseSVN. The main program to work with here is TortoiseProc.exe
.
But a note pretty much at the top there already says:
Remember that TortoiseSVN is a GUI client, and this automation guide shows you how to make the TortoiseSVN dialogs appear to collect user input. If you want to write a script which requires no input, you should use the official Subversion command line client instead.
Another option would be that you install the Subversion binaries. Slik SVN is a nice build (and doesn't require a registration like Collabnet). Recent versions of TortoiseSVN also include the command-line client if you choose to install it.
I had this same problem in a Maven project. After creating the src/test/java folder within the project the error went away.
This way you can set the initial day of the week.
moment.locale('en', {
week: {
dow: 6
}
});
moment.locale('en');
Make sure to use it with moment().weekday(1);
instead of moment.isoWeekday(1)
If you have multiple source files, you probably actually want to use link-time-optimization to output one bitcode file for the entire program. The other answers given will cause you to end up with a bitcode file for every source file.
Instead, you want to compile with link-time-optimization
clang -flto -c program1.c -o program1.o
clang -flto -c program2.c -o program2.o
and for the final linking step, add the argument -Wl,-plugin-opt=also-emit-llvm
clang -flto -Wl,-plugin-opt=also-emit-llvm program1.o program2.o -o program
This gives you both a compiled program and the bitcode corresponding to it (program.bc). You can then modify program.bc in any way you like, and recompile the modified program at any time by doing
clang program.bc -o program
although be aware that you need to include any necessary linker flags (for external libraries, etc) at this step again.
Note that you need to be using the gold linker for this to work. If you want to force clang to use a specific linker, create a symlink to that linker named "ld" in a special directory called "fakebin" somewhere on your computer, and add the option
-B/home/jeremy/fakebin
to any linking steps above.
For phpMyAdmin I figured this out:
SELECT GROUP_CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" SEPARATOR ' ') AS OneSQLString
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="yourtableschemaname"
AND TABLE_TYPE="BASE TABLE"
Just change yourtableschemaname and you're fine.
What I use:
set long 50000
set linesize 130
col x format a80 word_wrapped;
select dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA') x from dual;
Or am I missing something?
I dont think there is any sdk support for sending mms in android. Look here Atleast I havent found yet. But a guy claimed to have it. Have a look at this post.
Try this..
List<Cat> cats = new List<Cat>
{
new Cat(){ Name = "Sylvester", Age=8 },
new Cat(){ Name = "Whiskers", Age=2 },
new Cat(){ Name = "Sasha", Age=14 }
};
Session["data"] = cats;
foreach (Cat c in cats)
System.Diagnostics.Debug.WriteLine("Cats>>" + c.Name); //DEBUGGG
DESC KEYSPACES will do the job.
Also, If you want to describe schema of a particular keyspace you can use
DESC
It's kind of a hack, but I think this is probably the best way to do it. The dashed line will always be on the bottom, regardless of the height.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle" >
<solid android:color="#1bd4f6" />
</shape>
</item>
<item android:top="-2dp" android:right="-2dp" android:left="-2dp">
<shape>
<solid android:color="@android:color/transparent" />
<stroke
android:dashGap="10px"
android:dashWidth="10px"
android:width="1dp"
android:color="#ababb2" />
</shape>
</item>
</layer-list>
The second shape is transparent rectangle with a dashed outline. The key in making the border only appear along the bottom lies in the negative margins set the other sides. These negative margins "push" the dashed line outside the drawn area on those sides, leaving only the line along the bottom. One potential side-effect (which I haven't tried) is that, for views that draw outside their own bounds, the negative-margin borders may become visible.
This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.
The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...)
and cola<string>::cola(...)
until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T>
also.)
The problem is caused by the fact that main.cpp
and cola.cpp
will be compiled separately first. In main.cpp
, the compiler will implicitly instantiate the template classes cola<float>
and cola<string>
because those particular instantiations are used in main.cpp
. The bad news is that the implementations of those member functions are not in main.cpp
, nor in any header file included in main.cpp
, and therefore the compiler can't include complete versions of those functions in main.o
. When compiling cola.cpp
, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float>
or cola<string>
. Remember, when compiling cola.cpp
, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>
, cola<char>
, cola<ostream>
, cola< cola<int> >
... and so on ...)
The two answers are:
cola.cpp
, which particular template classes will be required, forcing it to compile cola<float>
and cola<string>
.main.cpp
) uses the template class.At the end of cola.cpp
, you should add lines explicitly instantiating all the relevant templates, such as
template class cola<float>;
template class cola<string>;
and you add the following two lines at the end of nodo_colaypila.cpp
:
template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;
This will ensure that, when the compiler is compiling cola.cpp
that it will explicitly compile all the code for the cola<float>
and cola<string>
classes. Similarly, nodo_colaypila.cpp
contains the implementations of the nodo_colaypila<...>
classes.
In this approach, you should ensure that all the of the implementation is placed into one .cpp
file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).
The common answer is to move all the code from the implementation files cola.cpp
and nodo_colaypila.cpp
into cola.h
and nodo_colaypila.h
. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>
) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.
The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float>
and cola<string>
, if you want to use something else, tell me first and will can verify it works before enabling it.").
Finally, there are three other minor typos in the code in your question:
#endif
at the end of nodo_colaypila.hnodo_colaypila<T>* ult, pri;
should be nodo_colaypila<T> *ult, *pri;
- both are pointers.nodo_colaypila.h
, not in this implementation file.You want the 'change' event handler, instead of 'click'.
$('#mySelect').change(function(){
var value = $(this).val();
});
scrollintoview()
increases usabilityInstead of default DOM implementation you can use a plugin that animates movement and doesn't have any unwanted effects. Here's the simplest way of using it with defaults:
$("yourTargetLiSelector").scrollintoview();
Anyway head over to this blog post where you can read all the details and will eventually get you to GitHub source codeof the plugin.
This plugin automatically searches for the closest scrollable ancestor element and scrolls it so that selected element is inside its visible view port. If the element is already in the view port it doesn't do anything of course.
You can directly access a global variable inside a function. If you want to change the value of that global variable, use "global variable_name". See the following example:
var = 1
def global_var_change():
global var
var = "value changed"
global_var_change() #call the function for changes
print var
Generally speaking, this is not a good programming practice. By breaking namespace logic, code can become difficult to understand and debug.
If you're following the "github fork" workflow, where you create a fork and add the remote upstream repo:
14:47 $ git remote -v
origin [email protected]:<yourname>/<repo_name>.git (fetch)
origin [email protected]:<yourname>/<repo_name>.git (push)
upstream [email protected]:<repo_owrer>/<repo_name>.git (fetch)
upstream [email protected]:<repo_owner>/<repo_name>.git (push)
to pull into your current branch your command would look like:
git pull upstream pull/<pull_request_number>/head
to pull into a new branch the code would look like:
git fetch upstream pull/<pull_request_number>/head:newbranch
As of Room 1.1.0
you can use clearAllTables() which:
Deletes all rows from all the tables that are registered to this database as entities().
Try this:
string callbackurl = Request.Url.Host != "localhost"
? Request.Url.Host : Request.Url.Authority;
This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.
This will determine whether the browser is Safari or not.
if(navigator.userAgent.indexOf('Safari') !=-1 && navigator.userAgent.indexOf('Chrome') == -1)
{
alert(its safari);
}else {
alert('its not safari');
}
Yet another way
$("#wizard li").click(function ()
{
$($(this),'#wizard"').index();
});
If are you working with numbers a lot, you might want to take a look at NumPy. It lets you perform all kinds of operation directly on numerical arrays. For example:
>>> import numpy
>>> array = numpy.array([49, 51, 53, 56])
>>> array - 13
array([36, 38, 40, 43])
The only difference between isBlank() and isEmpty() is:
StringUtils.isBlank(" ") = true //compared string value has space and considered as blank
StringUtils.isEmpty(" ") = false //compared string value has space and not considered as empty
You received the good answer to this question, but I want to add my two cents. You could use one method and process requests according to request type:
public ActionResult Index()
{
if("GET"==this.HttpContext.Request.RequestType)
{
Some Code--Some Code---Some Code for GET
}
else if("POST"==this.HttpContext.Request.RequestType)
{
Some Code--Some Code---Some Code for POST
}
else
{
//exception
}
return View();
}
CASE
is an expression - it returns a single scalar value (per row). It can't return a complex part of the parse tree of something else, like an ORDER BY
clause of a SELECT
statement.
It looks like you just need:
ORDER BY
CASE WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount END desc,
CASE WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount END desc,
Case WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount END DESC,
CASE WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount END DESC,
Case WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount END DESC,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
Or possibly:
ORDER BY
CASE
WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
It's a little tricky to tell which of the above (or something else) is what you're looking for because you've a) not explained what actual sort order you're trying to achieve, and b) not supplied any sample data and expected results, from which we could attempt to deduce the actual sort order you're trying to achieve.
This may be the answer we're looking for:
ORDER BY
CASE
WHEN TblList.PinRequestCount <> 0 THEN 5
WHEN TblList.HighCallAlertCount <> 0 THEN 4
WHEN TblList.HighAlertCount <> 0 THEN 3
WHEN TblList.MediumCallAlertCount <> 0 THEN 2
WHEN TblList.MediumAlertCount <> 0 THEN 1
END desc,
CASE
WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
Here is a function to print a PDF from an iframe.
You just need to pass the URL of the PDF to the function. It will create an iframe and trigger print once the PDF is load.
Note that the function doesn't destroy the iframe. Instead, it reuses it each time the function is call. It's hard to destroy the iframe because it is needed until the printing is done, and the print method doesn't has callback support (as far as I know).
printPdf = function (url) {
var iframe = this._printIframe;
if (!this._printIframe) {
iframe = this._printIframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.onload = function() {
setTimeout(function() {
iframe.focus();
iframe.contentWindow.print();
}, 1);
};
}
iframe.src = url;
}
How to preventing decompilation of any C# application
Pretty much describes the entire situation.
At some point the code will have to be translated to VM bytecode, and the user can get at it then.
Machine code isn't that much different either. A good interactive disassembler/debugger like IDA Pro makes just about any native application transparent. The debugger is smart enough to use AI to identify common APIs, compiler optimizations, etc. it allows the user to meticuloulsy rebuild higher level constructs from the assembly generated from machine code.
And IDA Pro supports .Net to some extent too.
Honestly, after working on an reverse engineering ( for compatibility ) project for a few years, the main thing I got out of my experience is that I probably shouldn't worry too much about people stealing my code. If anyone wants it, it will never be very hard to get it no matter what scheme I implement.
Try this expression...
string-join(//element3/(concat(element4/text(), '.', element5/text())), " ")
Look at your code You defined DB_HOST and querying DB_SERVER. DB_USER and DB_USERNAME Use this code
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "databasename");
$connect = mysqli_connect(DB_SERVER , DB_USER, DB_PASSWORD, DB_DATABASE);
add following property in your hibernate.cfg.xml file
<property name="hibernate.hbm2ddl.auto">update</property>
BTW, in your Entity class, you must define your @Id filed like this:
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "id")
private long id;
if you use the following definition, it maybe not work:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
Following are few options available to change Heap Size.
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
java -Xmx256m TestData.java
This worked for me. Might want to try editing virtual machine settings:
I found a little known but amazingly cool way to do it from Payette's Windows Powershell in Action. You can reference files like variables, similar to $env:path, but you need to add the curly braces.
${c:file.txt} = ${c:file.txt} -replace 'oldvalue','newvalue'
This is all nicely lined up including the field label. Lining up the field label was the tricky part.
<div class="form-group">
<label class="control-label col-md-5">Create a</label>
<div class="col-md-7">
<label class="radio-inline control-label">
<input checked="checked" id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="2"> Task
</label>
<label class="radio-inline control-label">
<input id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="1"> Note
</label>
</div>
</div>
<div class="form-group">
@Html.Label("Create a", htmlAttributes: new { @class = "control-label col-md-5" })
<div class="col-md-7">
<label class="radio-inline control-label">
@Html.RadioButtonFor(model => model.TaskTypeId, Model.TaskTaskTypeId) Task
</label>
<label class="radio-inline control-label">
@Html.RadioButtonFor(model => model.TaskTypeId, Model.NoteTaskTypeId) Note
</label>
</div>
</div>
df=df.filter(df["columnname"]>='2020-01-13')
C++ uses structs primarily for 1) backwards compatibility with C and 2) POD types. C structs do not have methods, inheritance or visibility.
If you want to be able to show / hide singular divs and / or groups of divs with less code, just apply several classes to them, to insert them into groups if needed.
Example :
.group1 {}
.group2 {}
.group3 {}
<div class="group3"></div>
<div class="group1 group2"></div>
<div class="group1 group3 group2"></div>
Then you just need to use an identifier to link the action to he target, and with 5,6 lines of jquery code you have everything you need.
When you are trying to prevent XSS, it's important to think of the context. As an example how and what to escape is very different if you are ouputting data inside a variable in a javascript snippet as opposed to outputting data in an HTML tag or an HTML attribute.
I have an example of this here: http://erlend.oftedal.no/blog/?blogid=91
Also checkout the OWASP XSS Prevention Cheat Sheet: http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
So the short answer is, make sure you escape output like suggested by Tendayi Mawushe, but take special care when you are outputting data in HTML attributes or javascript.
With standart binding you need to use converters that looks little windy. So, I recommend you to look at my project CalcBinding, which was developed specially to resolve this problem and some others. With advanced binding you can write expressions with many source properties directly in xaml. Say, you can write something like:
<Button IsEnabled="{c:Binding Path=!IsReadOnly}" />
or
<Button Content="{c:Binding ElementName=grid, Path=ActualWidth+Height}"/>
or
<Label Content="{c:Binding A+B+C }" />
or
<Button Visibility="{c:Binding IsChecked, FalseToVisibility=Hidden}" />
where A, B, C, IsChecked - properties of viewModel and it will work properly
There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0
tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.
The closest link I could find to be useful for more information is this
Quote from above link:
What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.
From the Documentation for GetEXitCodeThread
Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.
My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.
Download this Sqlite manager its the easiest one to use Sqlite manager
and drag and drop your fetched file on its running instance
only drawback of this Sqlite Manager it stop responding if you run some SQL statement that has Syntax Error in it.
So i Use Firefox Plugin Side by side also which you can find at FireFox addons
For a PHP approach, you can use mysql_field_flags
$q = mysql_query('select * from table limit 1');
for($i = 0; $i < mysql_num_fields(); $i++)
if(strpos(mysql_field_tags($q, $i), 'primary_key') !== false)
echo mysql_field_name($q, $i)." is a primary key\n";
Just a side note for similar problem (If we don't want to loop through):
How to lookup a dictionary using a variable key within Jinja template?
Here is an example:
{% set key = target_db.Schema.upper()+"__"+target_db.TableName.upper() %}
{{ dict_containing_df.get(key).to_html() | safe }}
It might be obvious. But we don't need curly braces within curly braces. Straight python syntax works. (I am posting because I was confusing to me...)
Alternatively, you can simply do
{{dict[target_db.Schema.upper()+"__"+target_db.TableName.upper()]).to_html() | safe }}
But it will spit an error when no key is found. So better to use get
in Jinja.
With Spring, you can use this:
import org.springframework.core.io.ClassPathResource;
// Don't worry when use a not existed directory or a empty directory
// It can be used in @before
String dir = new ClassPathResource(".").getFile().getAbsolutePath()+"/"+"Your Path";
And in addition to the above nice answers.
RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman.
Delete or rename the 2 following files from "C:\ProgramData\MySQL\MySQL Server 5.7\Data": ib_logfile0 ib_logfile1
"
git fetch
" (hence "git pull
" as well) learned to check "fetch.prune
" and "remote.*.prune
" configuration variables and to behave as if the "--prune
" command line option was given.
That means that, if you set remote.origin.prune to true:
git config remote.origin.prune true
Any git fetch
or git pull
will automatically prune.
Note: Git 2.12 (Q1 2017) will fix a bug related to this configuration, which would make git remote rename
misbehave.
See "How do I rename a git remote?".
See more at commit 737c5a9:
Without "
git fetch --prune
", remote-tracking branches for a branch the other side already has removed will stay forever.
Some people want to always run "git fetch --prune
".To accommodate users who want to either prune always or when fetching from a particular remote, add two new configuration variables "
fetch.prune
" and "remote.<name>.prune
":
- "
fetch.prune
" allows to enable prune for all fetch operations.- "
remote.<name>.prune
" allows to change the behaviour per remote.The latter will naturally override the former, and the
--[no-]prune
option from the command line will override the configured default.Since
--prune
is a potentially destructive operation (Git doesn't keep reflogs for deleted references yet), we don't want to prune without users consent, so this configuration will not be on by default.
Another option,especially useful if you have many items you need to pivot is to let mysql build the query for you:
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'ifnull(SUM(case when itemname = ''',
itemname,
''' then itemvalue end),0) AS `',
itemname, '`'
)
) INTO @sql
FROM
history;
SET @sql = CONCAT('SELECT hostid, ', @sql, '
FROM history
GROUP BY hostid');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
FIDDLE Added some extra values to see it working
GROUP_CONCAT
has a default value of 1000 so if you have a really big query change this parameter before running it
SET SESSION group_concat_max_len = 1000000;
Test:
DROP TABLE IF EXISTS history;
CREATE TABLE history
(hostid INT,
itemname VARCHAR(5),
itemvalue INT);
INSERT INTO history VALUES(1,'A',10),(1,'B',3),(2,'A',9),
(2,'C',40),(2,'D',5),
(3,'A',14),(3,'B',67),(3,'D',8);
hostid A B C D
1 10 3 0 0
2 9 0 40 5
3 14 67 0 8
Try using TempData
:
public ActionResult Create(FormCollection collection) {
...
TempData["notice"] = "Successfully registered";
return RedirectToAction("Index");
...
}
Then, in your Index view, or master page, etc., you can do this:
<% if (TempData["notice"] != null) { %>
<p><%= Html.Encode(TempData["notice"]) %></p>
<% } %>
Or, in a Razor view:
@if (TempData["notice"] != null) {
<p>@TempData["notice"]</p>
}
Quote from MSDN (page no longer exists as of 2014, archived copy here):
An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.
have a look at vsnprintf as this will do what ya want http://www.cplusplus.com/reference/clibrary/cstdio/vsprintf/
you will have to init the va_list arg array first, then call it.
Example from that link: /* vsprintf example */
#include <stdio.h>
#include <stdarg.h>
void Error (char * format, ...)
{
char buffer[256];
va_list args;
va_start (args, format);
vsnprintf (buffer, 255, format, args);
//do something with the error
va_end (args);
}
I am not completely sure what you're trying to achieve by seeking to a specific offset and attempting to load individual values manually, the typical usage of the pickle
module is:
# save data to a file
with open('myfile.pickle','wb') as fout:
pickle.dump([1,2,3],fout)
# read data from a file
with open('myfile.pickle') as fin:
print pickle.load(fin)
# output
>> [1, 2, 3]
If you dumped a list, you'll load a list, there's no need to load each item individually.
you're saying that you got an error before you were seeking to the -5000 offset, maybe the file you're trying to read is corrupted.
If you have access to the original data, I suggest you try saving it to a new file and reading it as in the example.
Use the constructor that allows you to specify the year, month, day, hours, minutes, and seconds:
var dateNow = DateTime.Now;
var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 4, 5, 6);
For Python Run This Command
apt-get install -y python-setuptools
For Python 3.
apt-get install -y python3-setuptools
You would have to use the JavascriptExecutor class:
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('//id of element').setAttribute('attr', '10')");
Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.
if (data == "" || data == undefined) {
alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
var byteCharacters = atob(data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {
type: 'application/pdf'
});
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else { // Directly use base 64 encoded data for rest browsers (not IE)
var base64EncodedPDF = data;
var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
window.open(dataURI, '_blank');
}
}
I had the same issue on my React Native Project. Was not just that ADV Manager didn't show up on the menu but other tools where missing as well.
Everything was back to normal when I opened the project using Import project option instead of Open an Existing Android Studio project.
Although this question has several answers, they may now be a little dated.
New readers may prefer to consider the xlsx or "sheetsJS" package, which now seems to now be by far the most popular node package for this use case.
The current top answer recommends excel4node , which does look quite good - but the latter package seems less maintained (and far less popular) than the former.
Answering the question directly, using xlsx:
const XLSX = require('xlsx');
/* create a new blank workbook */
const wb = XLSX.utils.book_new();
// Do stuff, write data
//
//
// write the workbook object to a file
XLSX.writeFile(workbook, 'out.xlsx');
ACTIONS = {
1 : "Created",
2 : "Deleted",
3 : "Updated",
4 : "Renamed from something",
5 : "Renamed to something"
}
FILE_LIST_DIRECTORY = 0x0001
class myThread (threading.Thread):
def __init__(self, threadID, fileName, directory, origin):
threading.Thread.__init__(self)
self.threadID = threadID
self.fileName = fileName
self.daemon = True
self.dir = directory
self.originalFile = origin
def run(self):
startMonitor(self.fileName, self.dir, self.originalFile)
def startMonitor(fileMonitoring,dirPath,originalFile):
hDir = win32file.CreateFile (
dirPath,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None
)
# Wait for new data and call ProcessNewData for each new chunk that's
# written
while 1:
# Wait for a change to occur
results = win32file.ReadDirectoryChangesW (
hDir,
1024,
False,
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
None,
None
)
# For each change, check to see if it's updating the file we're
# interested in
for action, file_M in results:
full_filename = os.path.join (dirPath, file_M)
#print file, ACTIONS.get (action, "Unknown")
if len(full_filename) == len(fileMonitoring) and action == 3:
#copy to main file
...
For some reason shadows don't work if you set <solid>
AND <stroke>
on your custom background drawable. Creating a <layer-list>
with separate layers for fill and borders fixes the issue:
<?xml version="1.0" encoding="utf-8"?>
<!-- Separate layers for solid and stroke, because no shadows get drawn otherwise (using elevation) -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/card_default" />
<corners android:radius="@dimen/card_corner_radius" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<stroke android:color="@color/card_border" android:width="@dimen/card_border_width"/>
<corners android:radius="@dimen/card_corner_radius" />
</shape>
</item>
</layer-list>
Sort and Lock Table is the only solution I have seen which does work on other browsers than IE. (although this "locked column css" might do the trick as well). Required code block below.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script type="text/javascript" src="/js/lib/dummy.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type="text/css">
/* Scrollable Content Height */
.scrollContent {
height:100px;
overflow-x:hidden;
overflow-y:auto;
}
.scrollContent tr {
height: auto;
white-space: nowrap;
}
/* Prevent Mozilla scrollbar from hiding right-most cell content */
.scrollContent tr td:last-child {
padding-right: 20px;
}
/* Fixed Header Height */
.fixedHeader tr {
position: relative;
height: auto;
}
/* Put border around entire table */
div.TableContainer {
border: 1px solid #7DA87D;
}
/* Table Header formatting */
.headerFormat {
background-color: white;
color: #FFFFFF;
margin: 3px;
padding: 1px;
white-space: nowrap;
font-family: Helvetica;
font-size: 16px;
text-decoration: none;
font-weight: bold;
}
.headerFormat tr td {
border: 1px solid #000000;
background-color: #7DA87D;
}
/* Table Body (Scrollable Content) formatting */
.bodyFormat tr td {
color: #000000;
margin: 3px;
padding: 1px;
border: 0px none;
font-family: Helvetica;
font-size: 12px;
}
/* Use to set different color for alternating rows */
.alternateRow {
background-color: #E0F1E0;
}
/* Styles used for SORTING */
.point {
cursor:pointer;
}
td.sortedColumn {
background-color: #E0F1E0;
}
tr.alternateRow td.sortedColumn {
background-color: #c5e5c5;
}
.total {
background-color: #FED362;
color: #000000;
white-space: nowrap;
font-size: 12px;
text-decoration: none;
}
</style>
<title></title>
<script type='text/javascript'>//<![CDATA[
/* This script and many more are available free online at
The JavaScript Source :: http://www.javascriptsource.com
Created by: Stan Slaughter :: http://www.stansight.com/ */
/* ======================================================
Generic Table Sort
Basic Concept: A table can be sorted by clicking on the title of any
column in the table, toggling between ascending and descending sorts.
Assumptions:
* The first row of the table contains column titles that are "clicked"
to sort the table
* The images 'desc.gif','asc.gif','none.gif','sorting.gif' exist
* The img tag is in each column of the the title row to represent the
sort graphic.
* The CSS classes 'alternateRow' and 'sortedColumn' exist so we can
have alternating colors for each row and a highlight the sorted
column. Something like the <style> definition below, but with the
background colors set to whatever you want.
<style>
tr.alternateRow {
background-color: #E0F1E0;
}
td.sortedColumn {
background-color: #E0F1E0;
}
tr.alternateRow td.sortedColumn {
background-color: #c5e5c5;
}
</style>
====================================================== */
function sortTable(td_element,ignoreLastLines) {
// If the optional ignoreLastLines parameter (number of lines *not* to sort at end of table)
// was not passed then make it 0
ignoreLastLines = (typeof(ignoreLastLines)=='undefined') ? 0 : ignoreLastLines;
var sortImages =['data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUz4IVcZDleixQIQjA1pFFZx2FVRklZvOWUl8LsVgBeFLyE8TLgDZYESISwvAAA1QvjAQwBADs=','data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUw4CVeDzOeFwCgIhFBBDtY1sAmtIIWFV0VJweNRhkZeoeDpWIQNSYBgSAgWYgQLGwIADs=','data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7','http://web.archive.org/web/20150906203819im_/http://www.javascriptsource.com/miscellaneous/sorting.gif'];
// Get the image used in the first row of the current column
var sortColImage = td_element.getElementsByTagName('img')[0];
// If current image is 'asc.gif' or 'none.gif' (elements 1 and 2 of sortImages array) then this will
// be a descending sort else it will be ascending - get new sort image icon and set sort order flag
var sortAscending = false;
var newSortColImage = "";
if (sortColImage.getAttribute('src').indexOf(sortImages[1])>-1 ||
sortColImage.getAttribute('src').indexOf(sortImages[2])>-1) {
newSortColImage = sortImages[0];
sortAscending = false;
} else {
newSortColImage = sortImages[1];
sortAscending = true;
}
// Assign "SORTING" image icon (element 3 of sortImages array)) to current column title
// (will replace with newSortColImage when sort completes)
sortColImage.setAttribute('src',sortImages[3]);
// Find which column was clicked by getting it's column position
var indexCol = td_element.cellIndex;
// Get the table element from the td element that was passed as a parameter to this function
var table_element = td_element.parentNode;
while (table_element.nodeName != "TABLE") {
table_element = table_element.parentNode;
}
// Get all "tr" elements from the table and assign then to the Array "tr_elements"
var tr_elements = table_element.getElementsByTagName('tr');
// Get all the images used in the first row then set them to 'none.gif'
// (element 2 or sortImages array) except for the current column (all ready been changed)
var allImg = tr_elements[0].getElementsByTagName('img');
for(var i=0;i<allImg.length;i++){
if(allImg[i]!=sortColImage){allImg[i].setAttribute('src',sortImages[2])}
}
// Some explantion of the basic concept of the following code before we
// actually start. Essentially we are going to copy the current columns information
// into an array to be sorted. We'll sort the column array then go back and use the information
// we saved about the original row positions to re-order the entire table.
// We are never really sorting more than a columns worth of data, which should keep the sorting fast.
// Create a new array for holding row information
var clonedRows = new Array()
// Create a new array to store just the selected column values, not the whole row
var originalCol = new Array();
// Now loop through all the data row elements
// NOTE: Starting at row 1 because row 0 contains the column titles
for (var i=1; i<tr_elements.length - ignoreLastLines; i++) {
// "Clone" the tr element i.e. save a copy all of its attributes and values
clonedRows[i]=tr_elements[i].cloneNode(true);
// Text value of the selected column on this row
var valueCol = getTextValue(tr_elements[i].cells[indexCol]);
// Format text value for sorting depending on its type, ie Date, Currency, number, etc..
valueCol = FormatForType(valueCol);
// Assign the column value AND the row number it was originally on in the table
originalCol[i]=[valueCol,tr_elements[i].rowIndex];
}
// Get rid of element "0" from this array. A value was never assigned to it because the first row
// in the table just contained the column titles, which we did not bother to assign.
originalCol.shift();
// Sort the column array returning the value of a sort into a new array
sortCol = originalCol.sort(sortCompare);
// If it was supposed to be an Ascending sort then reverse the order
if (sortAscending) { sortCol.reverse(); }
// Now take the values from the sorted column array and use that information to re-arrange
// the order of the tr_elements in the table
for (var i=1; i < tr_elements.length - ignoreLastLines; i++) {
var old_row = sortCol[i-1][1];
var new_row = i;
tr_elements[i].parentNode.replaceChild(clonedRows[old_row],tr_elements[new_row]);
}
// Format the table, making the rows alternating colors and highlight the sorted column
makePretty(table_element,indexCol,ignoreLastLines);
// Assign correct sort image icon to current column title
sortColImage.setAttribute('src',newSortColImage);
}
// Function used by the sort routine to compare the current value in the array with the next one
function sortCompare (currValue, nextValue) {
// Since the elements of this array are actually arrays themselves, just sort
// on the first element which contiains the value, not the second which contains
// the original row position
if ( currValue[0] == nextValue[0] ) return 0;
if ( currValue[0] < nextValue[0] ) return -1;
if ( currValue[0] > nextValue[0] ) return 1;
}
//-----------------------------------------------------------------------------
// Functions to get and compare values during a sort.
//-----------------------------------------------------------------------------
// This code is necessary for browsers that don't reflect the DOM constants
// (like IE).
if (document.ELEMENT_NODE == null) {
document.ELEMENT_NODE = 1;
document.TEXT_NODE = 3;
}
function getTextValue(el) {
var i;
var s;
// Find and concatenate the values of all text nodes contained within the
// element.
s = "";
for (i = 0; i < el.childNodes.length; i++)
if (el.childNodes[i].nodeType == document.TEXT_NODE)
s += el.childNodes[i].nodeValue;
else if (el.childNodes[i].nodeType == document.ELEMENT_NODE &&
el.childNodes[i].tagName == "BR")
s += " ";
else
// Use recursion to get text within sub-elements.
s += getTextValue(el.childNodes[i]);
return normalizeString(s);
}
// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");
function normalizeString(s) {
s = s.replace(whtSpMult, " "); // Collapse any multiple whites space.
s = s.replace(whtSpEnds, ""); // Remove leading or trailing white space.
return s;
}
// Function used to modify values to make then sortable depending on the type of information
function FormatForType(itm) {
var sortValue = itm.toLowerCase();
// If the item matches a date pattern (MM/DD/YYYY or MM/DD/YY or M/DD/YYYY)
if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/) ||
itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/) ||
itm.match(/^\d[\/-]\d\d[\/-]\d\d\d\d$/) ) {
// Convert date to YYYYMMDD format for sort comparison purposes
// y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
var yr = -1;
if (itm.length == 10) {
sortValue = itm.substr(6,4)+itm.substr(0,2)+itm.substr(3,2);
} else if (itm.length == 9) {
sortValue = itm.substr(5,4)+"0" + itm.substr(0,1)+itm.substr(2,2);
} else {
yr = itm.substr(6,2);
if (parseInt(yr) < 50) {
yr = '20'+yr;
} else {
yr = '19'+yr;
}
sortValue = yr+itm.substr(3,2)+itm.substr(0,2);
}
}
// If the item matches a Percent patten (contains a percent sign)
if (itm.match(/%/)) {
// Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
sortValue = itm.replace(/[^0-9.-]/g,'');
sortValue = parseFloat(sortValue);
}
// If item starts with a "(" and ends with a ")" then remove them and put a negative sign in front
if (itm.substr(0,1) == "(" & itm.substr(itm.length - 1,1) == ")") {
itm = "-" + itm.substr(1,itm.length - 2);
}
// If the item matches a currency pattern (starts with a dollar or negative dollar sign)
if (itm.match(/^[£$]|(^-)/)) {
// Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
sortValue = itm.replace(/[^0-9.-]/g,'');
if (isNaN(sortValue)) {
sortValue = 0;
} else {
sortValue = parseFloat(sortValue);
}
}
// If the item matches a numeric pattern
if (itm.match(/(\d*,\d*$)|(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/)) {
// Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
sortValue = itm.replace(/[^0-9.-]/g,'');
// sortValue = sortValue.replace(/,/g,'');
if (isNaN(sortValue)) {
sortValue = 0;
} else {
sortValue = parseFloat(sortValue);
}
}
return sortValue;
}
//-----------------------------------------------------------------------------
// Functions to update the table appearance after a sort.
//-----------------------------------------------------------------------------
// Style class names.
var rowClsNm = "alternateRow";
var colClsNm = "sortedColumn";
// Regular expressions for setting class names.
var rowTest = new RegExp(rowClsNm, "gi");
var colTest = new RegExp(colClsNm, "gi");
function makePretty(tblEl, col, ignoreLastLines) {
var i, j;
var rowEl, cellEl;
// Set style classes on each row to alternate their appearance.
for (i = 1; i < tblEl.rows.length - ignoreLastLines; i++) {
rowEl = tblEl.rows[i];
rowEl.className = rowEl.className.replace(rowTest, "");
if (i % 2 != 0)
rowEl.className += " " + rowClsNm;
rowEl.className = normalizeString(rowEl.className);
// Set style classes on each column (other than the name column) to
// highlight the one that was sorted.
for (j = 0; j < tblEl.rows[i].cells.length; j++) {
cellEl = rowEl.cells[j];
cellEl.className = cellEl.className.replace(colTest, "");
if (j == col)
cellEl.className += " " + colClsNm;
cellEl.className = normalizeString(cellEl.className);
}
}
}
// END Generic Table sort.
// =================================================
// Function to scroll to top before sorting to fix an IE bug
// Which repositions the header off the top of the screen
// if you try to sort while scrolled to bottom.
function GoTop() {
document.getElementById('TableContainer').scrollTop = 0;
}
//]]>
</script>
</head>
<body>
<table cellpadding="0" cellspacing="0" border="0">
<tr><td>
<div id="TableContainer" class="TableContainer" style="height:230px;">
<table class="scrollTable">
<thead class="fixedHeader headerFormat">
<tr>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort"><b>NAME</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Amt</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Lvl</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Rank</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Position</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
<td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Date</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
</tr>
</thead>
<tbody class="scrollContent bodyFormat" style="height:200px;">
<tr class="alternateRow">
<td>Maha</td>
<td align="right">$19,923.19</td>
<td align="right">100</td>
<td align="right">100</td>
<td>Owner</td>
<td align="right">01/02/2001</td>
</tr>
<tr>
<td>Thrawl</td>
<td align="right">$9,550</td>
<td align="right">159</td>
<td align="right">100%</td>
<td>Co-Owner</td>
<td align="right">11/07/2003</td>
</tr>
<tr class="alternateRow">
<td>Marhanen</td>
<td align="right">$223.04</td>
<td align="right">83</td>
<td align="right">99%</td>
<td>Banker</td>
<td align="right">06/27/2006</td>
</tr>
<tr>
<td>Peter</td>
<td align="right">$121</td>
<td align="right">567</td>
<td align="right">23423%</td>
<td>FishHead</td>
<td align="right">06/06/2006</td>
</tr>
<tr class="alternateRow">
<td>Jones</td>
<td align="right">$15</td>
<td align="right">11</td>
<td align="right">15%</td>
<td>Bubba</td>
<td align="right">10/27/2005</td>
</tr>
<tr>
<td>Supa-De-Dupa</td>
<td align="right">$145</td>
<td align="right">91</td>
<td align="right">32%</td>
<td>momma</td>
<td align="right">12/15/1996</td>
</tr>
<tr class="alternateRow">
<td>ClickClock</td>
<td align="right">$1,213</td>
<td align="right">23</td>
<td align="right">1%</td>
<td>Dada</td>
<td align="right">1/30/1998</td>
</tr>
<tr>
<td>Mrs. Robinson</td>
<td align="right">$99</td>
<td align="right">99</td>
<td align="right">99%</td>
<td>Wife</td>
<td align="right">07/04/1963</td>
</tr>
<tr class="alternateRow">
<td>Maha</td>
<td align="right">$19,923.19</td>
<td align="right">100</td>
<td align="right">100%</td>
<td>Owner</td>
<td align="right">01/02/2001</td>
</tr>
<tr>
<td>Thrawl</td>
<td align="right">$9,550</td>
<td align="right">159</td>
<td align="right">100%</td>
<td>Co-Owner</td>
<td align="right">11/07/2003</td>
</tr>
<tr class="alternateRow">
<td>Marhanen</td>
<td align="right">$223.04</td>
<td align="right">83</td>
<td align="right">59%</td>
<td>Banker</td>
<td align="right">06/27/2006</td>
</tr>
<tr>
<td>Peter</td>
<td align="right">$121</td>
<td align="right">567</td>
<td align="right">534.23%</td>
<td>FishHead</td>
<td align="right">06/06/2006</td>
</tr>
<tr class="alternateRow">
<td>Jones</td>
<td align="right">$15</td>
<td align="right">11</td>
<td align="right">15%</td>
<td>Bubba</td>
<td align="right">10/27/2005</td>
</tr>
<tr>
<td>Supa-De-Dupa</td>
<td align="right">$145</td>
<td align="right">91</td>
<td align="right">42%</td>
<td>momma</td>
<td align="right">12/15/1996</td>
</tr>
<tr class="alternateRow">
<td>ClickClock</td>
<td align="right">$1,213</td>
<td align="right">23</td>
<td align="right">2%</td>
<td>Dada</td>
<td align="right">1/30/1998</td>
</tr>
<tr>
<td>Mrs. Robinson</td>
<td align="right">$99</td>
<td align="right">99</td>
<td align="right">(-10.42%)</td>
<td>Wife</td>
<td align="right">07/04/1963</td>
</tr>
<tr class="alternateRow">
<td>Maha</td>
<td align="right">-$19,923.19</td>
<td align="right">100</td>
<td align="right">(-10.01%)</td>
<td>Owner</td>
<td align="right">01/02/2001</td>
</tr>
<tr>
<td>Thrawl</td>
<td align="right">$9,550</td>
<td align="right">159</td>
<td align="right">-10.20%</td>
<td>Co-Owner</td>
<td align="right">11/07/2003</td>
</tr>
<tr class="total">
<td><strong>TOTAL</strong>:</td>
<td align="right"><strong>999999</strong></td>
<td align="right"><strong>9999999</strong></td>
<td align="right"><strong>99</strong></td>
<td > </td>
<td align="right"> </td>
</tr>
</tbody>
</table>
</div>
</td></tr>
</table>
</body>
</html>
ok i figure out :
DECLARE @dayName VARCHAR(9), @weekenda VARCHAR(9), @free INT
SET @weekenda =DATENAME(dw,GETDATE())
IF (@weekenda='Saturday' OR @weekenda='Sunday')
SET @free=1
ELSE
SET @free=0
than i use : .......... OR free=1
Using SSMS, I made sure the user had connect permissions on both the database and ReportServer.
On the specific database being queried, under properties, I mapped their credentials and enabled datareader and public permissions. Also, as others have stated-I made sure there were no denyread/denywrite boxes selected.
I did not want to enable db ownership when for their reports since they only needed to have select permissions.
If you use %pylab inline
you can (on a new line) insert the following command:
%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)
This will set all figures in your document (unless otherwise specified) to be of the size (10, 6)
, where the first entry is the width and the second is the height.
See this SO post for more details. https://stackoverflow.com/a/17231361/1419668
Both do different things.
The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }
) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;
The second creates an object with dynamic storage duration and allows two things:
Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete
;
Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)
Neither is preferred; it depends on what you're doing as to which is most appropriate.
Use the former unless you need to use the latter.
Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.
Good luck.
Your original code is broken, as it delete
s a char
array that it did not new
. In fact, nothing new
d the C-style string; it came from a string literal. delete
ing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).
Usually an object should not have the responsibility of delete
ing anything that it didn't itself new
. This behaviour should be well-documented. In this case, the rule is being completely broken.
I've profiled Justins two solutions. a.Any(a => b.Contains(a))
is fastest.
using System;
using System.Collections.Generic;
using System.Linq;
namespace AnswersOnSO
{
public class Class1
{
public static void Main(string []args)
{
// How to check if list A contains any value from list B?
// e.g. something like A.contains(a=>a.id = B.id)?
var a = new List<int> {1,2,3,4};
var b = new List<int> {2,5};
var times = 10000000;
DateTime dtAny = DateTime.Now;
for (var i = 0; i < times; i++)
{
var aContainsBElements = a.Any(b.Contains);
}
var timeAny = (DateTime.Now - dtAny).TotalSeconds;
DateTime dtIntersect = DateTime.Now;
for (var i = 0; i < times; i++)
{
var aContainsBElements = a.Intersect(b).Any();
}
var timeIntersect = (DateTime.Now - dtIntersect).TotalSeconds;
// timeAny: 1.1470656 secs
// timeIn.: 3.1431798 secs
}
}
}
Install the gd library also.
check this link http://www.php.net/manual/en/mbstring.installation.php
git revert
is used to undo a previous commit. In git, you can't alter or erase an earlier commit. (Actually you can, but it can cause problems.) So instead of editing the earlier commit, revert introduces a new commit that reverses an earlier one.git reset
is used to undo changes in your working directory that haven't been comitted yet.git checkout
is used to copy a file from some other commit to your current working tree. It doesn't automatically commit the file.To get the entire contents of a file:
$content = [IO.File]::ReadAllText(".\test.txt")
Number of lines:
([IO.File]::ReadAllLines(".\test.txt")).length
or
(gc .\test.ps1).length
Sort of hackish to include trailing empty line:
[io.file]::ReadAllText(".\desktop\git-python\test.ps1").split("`n").count
Alright, so let's first start with making the distinction between Javascript in a web browser, and Javascript on a server (CommonJS and Node).
Javascript is a language traditionally confined to a web browser with a limited global context defined mostly by what came to be known as the Document Object Model (DOM) level 0 (the Netscape Navigator Javascript API).
Server-side Javascript eliminates that restriction and allows Javascript to call into various pieces of native code (like the Postgres library) and open sockets.
Now require()
is a special function call defined as part of the CommonJS spec. In node, it resolves libraries and modules in the Node search path, now usually defined as node_modules
in the same directory (or the directory of the invoked javascript file) or the system-wide search path.
To try to answer the rest of your question, we need to use a proxy between the code running in the the browser and the database server.
Since we are discussing Node and you are already familiar with how to run a query from there, it would make sense to use Node as that proxy.
As a simple example, we're going to make a URL that returns a few facts about a Beatle, given a name, as JSON.
/* your connection code */
var express = require('express');
var app = express.createServer();
app.get('/beatles/:name', function(req, res) {
var name = req.params.name || '';
name = name.replace(/[^a-zA_Z]/, '');
if (!name.length) {
res.send({});
} else {
var query = client.query('SELECT * FROM BEATLES WHERE name =\''+name+'\' LIMIT 1');
var data = {};
query.on('row', function(row) {
data = row;
res.send(data);
});
};
});
app.listen(80, '127.0.0.1');
I have tried almost all the answers and some of them almost worked for me but none of these answers work perfectly. So here is my solution. For this solution, you will need to add onclick
attribute in the HTML body tag. So if you can not modify the HTML file then this solution won't work for you.
Step 1: add onclick
attribute in the HTML body tag like this:
<body onclick="ok.performClick(this.value);">
<h1>This is heading 1</h1>
<p>This is para 1</p>
</body>
Step 2: implement addJavascriptInterface
in your app to handle click listener:
webView.addJavascriptInterface(new Object() {
@JavascriptInterface
public void performClick(String string) {
handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 0);
}
}, "ok");
Step 3: We can not perform any action on main thread from performClick
method so need to add Handler
class:
private final Handler handler = new Handler(this); // class-level variable
private static final int CLICK_ON_WEBVIEW = 1; // class-level variable
implement Handler.Callback
to your class and the override handleMessage
@Override
public boolean handleMessage(Message message) {
if (message.what == CLICK_ON_WEBVIEW) {
Toast.makeText(getActivity(), "WebView clicked", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
You can easily set like this: spinner.setSelection(1)
, instead of 1, you can set any position of list you would like to show.
You have to set the proper font path. e.g.
$fa-font-path:"../node_modules/font-awesome/fonts";
@import "../node_modules/font-awesome/scss/font-awesome";
.icon-user {
@extend .fa;
@extend .fa-user;
}
If you only wanna auto-completion from cache of your current buffers, supertab is easier to install than neocomplete, can work on Mac pre-installed vim out of box without the need of MacVim.
You can check other alternatives at vim awesome.
See C++ FAQ Lite How do I convert a std::string to a number?
See C++ Super-FAQ How do I convert a std::string to a number?
Please note that with your requirements you can't distinguish all the the allowed string representations of zero from the non numerical strings.
// the requested function
#include <sstream>
double string_to_double( const std::string& s )
{
std::istringstream i(s);
double x;
if (!(i >> x))
return 0;
return x;
}
// some tests
#include <cassert>
int main( int, char** )
{
// simple case:
assert( 0.5 == string_to_double( "0.5" ) );
// blank space:
assert( 0.5 == string_to_double( "0.5 " ) );
assert( 0.5 == string_to_double( " 0.5" ) );
// trailing non digit characters:
assert( 0.5 == string_to_double( "0.5a" ) );
// note that with your requirements you can't distinguish
// all the the allowed string representation of zero from
// the non numerical strings:
assert( 0 == string_to_double( "0" ) );
assert( 0 == string_to_double( "0." ) );
assert( 0 == string_to_double( "0.0" ) );
assert( 0 == string_to_double( "0.00" ) );
assert( 0 == string_to_double( "0.0e0" ) );
assert( 0 == string_to_double( "0.0e-0" ) );
assert( 0 == string_to_double( "0.0e+0" ) );
assert( 0 == string_to_double( "+0" ) );
assert( 0 == string_to_double( "+0." ) );
assert( 0 == string_to_double( "+0.0" ) );
assert( 0 == string_to_double( "+0.00" ) );
assert( 0 == string_to_double( "+0.0e0" ) );
assert( 0 == string_to_double( "+0.0e-0" ) );
assert( 0 == string_to_double( "+0.0e+0" ) );
assert( 0 == string_to_double( "-0" ) );
assert( 0 == string_to_double( "-0." ) );
assert( 0 == string_to_double( "-0.0" ) );
assert( 0 == string_to_double( "-0.00" ) );
assert( 0 == string_to_double( "-0.0e0" ) );
assert( 0 == string_to_double( "-0.0e-0" ) );
assert( 0 == string_to_double( "-0.0e+0" ) );
assert( 0 == string_to_double( "foobar" ) );
return 0;
}
I had the same problem. I solved it by running these 2 commands:
brew uninstall vapor
brew install vapor/tap/vapor
It worked.
jupyter nbconvert testing.ipynb --to html --no-input
for(int i=0;i<n;i++)
{
for(int j=str[i].length();j<4;j++)
str[i]="0".concat(str[i]);
}
str[i].length()
is length of number say 2 in binary is 01 which is length 2
change 4 to desired max length of number. This can be optimized to O(n).
by using continue.
Use Radium!
The following is an example from their website:
var Radium = require('radium');_x000D_
var React = require('react');_x000D_
var color = require('color');_x000D_
_x000D_
@Radium_x000D_
class Button extends React.Component {_x000D_
static propTypes = {_x000D_
kind: React.PropTypes.oneOf(['primary', 'warning']).isRequired_x000D_
};_x000D_
_x000D_
render() {_x000D_
// Radium extends the style attribute to accept an array. It will merge_x000D_
// the styles in order. We use this feature here to apply the primary_x000D_
// or warning styles depending on the value of the `kind` prop. Since its_x000D_
// all just JavaScript, you can use whatever logic you want to decide which_x000D_
// styles are applied (props, state, context, etc)._x000D_
return (_x000D_
<button_x000D_
style={[_x000D_
styles.base,_x000D_
styles[this.props.kind]_x000D_
]}>_x000D_
{this.props.children}_x000D_
</button>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
// You can create your style objects dynamically or share them for_x000D_
// every instance of the component._x000D_
var styles = {_x000D_
base: {_x000D_
color: '#fff',_x000D_
_x000D_
// Adding interactive state couldn't be easier! Add a special key to your_x000D_
// style object (:hover, :focus, :active, or @media) with the additional rules._x000D_
':hover': {_x000D_
background: color('#0074d9').lighten(0.2).hexString()_x000D_
}_x000D_
},_x000D_
_x000D_
primary: {_x000D_
background: '#0074D9'_x000D_
},_x000D_
_x000D_
warning: {_x000D_
background: '#FF4136'_x000D_
}_x000D_
};
_x000D_
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
Old question but now there is a simple solution, compatible with most browsers, which is to use CSS3
. I tested in IE, Firefox and Chrome and it works.
input[type="radio"] {
-ms-transform: scale(1.5); /* IE 9 */
-webkit-transform: scale(1.5); /* Chrome, Safari, Opera */
transform: scale(1.5);
}
Change the value 1.5
, in this case an increment of 50% in size, according to your needs. If the ratio is very high, it can blur the radio button. The next image shows a ratio of 1.5.
This is a part from a REST-Service I´ve written recently.
var select = $("#productSelect")
for (var prop in data) {
var option = document.createElement('option');
option.innerHTML = data[prop].ProduktName
option.value = data[prop].ProduktName;
select.append(option)
}
The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.
The introduction of some new testing facilities in Spring 4.2.RC1 lets one write Spring integration tests that don't rely on the SpringJUnit4ClassRunner
. Check out this part of the documentation.
In your case you could write your Spring integration test and still use mocks like this:
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration("test-app-ctx.xml")
public class FooTest {
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Autowired
@InjectMocks
TestTarget sut;
@Mock
Foo mockFoo;
@Test
public void someTest() {
// ....
}
}
To get just a correct number of dimensions in NumPy:
len(a.shape)
In the first case:
import numpy as np
a = np.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
print("shape = ",np.shape(a))
print("dimensions = ",len(a.shape))
The output will be:
shape = (2, 2, 3)
dimensions = 3
You can use isLetter(char c) static method of Character class in Java.lang .
public boolean isAlpha(String s) {
char[] charArr = s.toCharArray();
for(char c : charArr) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
Of course it does. After replacing the variable, it reads [ !-z ]
, which is not a valid [
command. Use double quotes, or [[
.
if [ ! -z "$errorstatus" ]
if [[ ! -z $errorstatus ]]
Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first
and second
members in your code:
std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };
for (const auto &[k, v] : myMap)
std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;
Output:
m[x] = (a, b)
m[y] = (c, d)
Try this
<input onkeypress='return event.charCode >= 48 && _x000D_
event.charCode <= 57 || _x000D_
event.charCode == 46'>
_x000D_
First, make your markup more portable/reusable. I also set the button's type to 'button'
instead of using the onsubmit
attribute. You can toggle the type
attribute to submit
if the form needs to interact with a server.
<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
<label id='nameLable' for='nameField'>Create a username:</label>
<input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
<button id='subButton' type='button'>Print your name!</button>
</div>
</form>
<div>
<p id='result'></p></div>
</div>
Next write a general function for retrieving the username into a variable. It checks to make sure the variable holding the username has it least three characters in it. You can change this to whatever constant you want.
function getUserName() {
var nameField = document.getElementById('nameField').value;
var result = document.getElementById('result');
if (nameField.length < 3) {
result.textContent = 'Username must contain at least 3 characters';
//alert('Username must contain at least 3 characters');
} else {
result.textContent = 'Your username is: ' + nameField;
//alert(nameField);
}
}
Next, I created an event listener for the button. It's generally considered the bad practice to have inline js calls.
var subButton = document.getElementById('subButton');
subButton.addEventListener('click', getUserName, false);
Here is a working and lightly styled demo:
Is it proper to "reach into" an object and use its dict property?
In general, I would say "no". However Namespace
has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.
On the other hand, Namespace
does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the __dict__
, but the limits of my imagination are not the same as yours.
Add '\t' for tab
<string name="tab">\u0009</string>
From the perspective of managing complexity, a primary software engineering objective, we want to avoid propagating unnecessary cyclomatic complexity to the clients of an API. Returning a null to the client is like returning them the cyclomatic complexity cost of another code branch.
(This corresponds to a unit testing burden. You would need to write a test for the null return case, in addition to the empty collection return case.)
I have many sites with this issue & finally found a fix to firefox fonts being thicker than chrome.
You need this line next to your -webkit fix -moz-osx-font-smoothing: grayscale;
body{
text-rendering: optimizeLegibility;
-webkit-font-smoothing: subpixel-antialiased;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
Most people are aware of the URL properties in document.location. That's great if you're only interested in the current page. But the question was about being able to parse anchors on a page not the page itself.
What most people seem to miss is that those same URL properties are also available to anchor elements:
// To process anchors on click
jQuery('a').click(function () {
if (this.hash) {
// Clicked anchor has a hash
} else {
// Clicked anchor does not have a hash
}
});
// To process anchors without waiting for an event
jQuery('a').each(function () {
if (this.hash) {
// Current anchor has a hash
} else {
// Current anchor does not have a hash
}
});
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
const dateObj = new Date();
const month = monthNames[dateObj.getMonth()];
const day = String(dateObj.getDate()).padStart(2, '0');
const year = dateObj.getFullYear();
const output = month + '\n'+ day + ',' + year;
document.querySelector('.date').textContent = output;
I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).
e.g. (from the doc)
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
I've tried to support the -ve values for @Ivan Stin excellent 2nd method. (Major credit goes to @Ivan Stin for his method)
public static float round(float value, int scale) {
int pow = 10;
for (int i = 1; i < scale; i++) {
pow *= 10;
}
float tmp = value * pow;
float tmpSub = tmp - (int) tmp;
return ( (float) ( (int) (
value >= 0
? (tmpSub >= 0.5f ? tmp + 1 : tmp)
: (tmpSub >= -0.5f ? tmp : tmp - 1)
) ) ) / pow;
// Below will only handles +ve values
// return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}
Below are the tests cases I've tried. Please let me know if this is not addressing any other cases.
@Test
public void testFloatRound() {
// +ve values
Assert.assertEquals(0F, NumberUtils.round(0F), 0);
Assert.assertEquals(1F, NumberUtils.round(1F), 0);
Assert.assertEquals(23.46F, NumberUtils.round(23.4567F), 0);
Assert.assertEquals(23.45F, NumberUtils.round(23.4547F), 0D);
Assert.assertEquals(1.00F, NumberUtils.round(0.49999999999999994F + 0.5F), 0);
Assert.assertEquals(123.12F, NumberUtils.round(123.123F), 0);
Assert.assertEquals(0.12F, NumberUtils.round(0.123F), 0);
Assert.assertEquals(0.55F, NumberUtils.round(0.55F), 0);
Assert.assertEquals(0.55F, NumberUtils.round(0.554F), 0);
Assert.assertEquals(0.56F, NumberUtils.round(0.556F), 0);
Assert.assertEquals(123.13F, NumberUtils.round(123.126F), 0);
Assert.assertEquals(123.15F, NumberUtils.round(123.15F), 0);
Assert.assertEquals(123.17F, NumberUtils.round(123.1666F), 0);
Assert.assertEquals(123.46F, NumberUtils.round(123.4567F), 0);
Assert.assertEquals(123.87F, NumberUtils.round(123.8711F), 0);
Assert.assertEquals(123.15F, NumberUtils.round(123.15123F), 0);
Assert.assertEquals(123.89F, NumberUtils.round(123.8909F), 0);
Assert.assertEquals(124.00F, NumberUtils.round(123.9999F), 0);
Assert.assertEquals(123.70F, NumberUtils.round(123.7F), 0);
Assert.assertEquals(123.56F, NumberUtils.round(123.555F), 0);
Assert.assertEquals(123.00F, NumberUtils.round(123.00F), 0);
Assert.assertEquals(123.50F, NumberUtils.round(123.50F), 0);
Assert.assertEquals(123.93F, NumberUtils.round(123.93F), 0);
Assert.assertEquals(123.93F, NumberUtils.round(123.9312F), 0);
Assert.assertEquals(123.94F, NumberUtils.round(123.9351F), 0);
Assert.assertEquals(123.94F, NumberUtils.round(123.9350F), 0);
Assert.assertEquals(123.94F, NumberUtils.round(123.93501F), 0);
Assert.assertEquals(99.99F, NumberUtils.round(99.99F), 0);
Assert.assertEquals(100.00F, NumberUtils.round(99.999F), 0);
Assert.assertEquals(100.00F, NumberUtils.round(99.9999F), 0);
// -ve values
Assert.assertEquals(-123.94F, NumberUtils.round(-123.93501F), 0);
Assert.assertEquals(-123.00F, NumberUtils.round(-123.001F), 0);
Assert.assertEquals(-0.94F, NumberUtils.round(-0.93501F), 0);
Assert.assertEquals(-1F, NumberUtils.round(-1F), 0);
Assert.assertEquals(-0.50F, NumberUtils.round(-0.50F), 0);
Assert.assertEquals(-0.55F, NumberUtils.round(-0.55F), 0);
Assert.assertEquals(-0.55F, NumberUtils.round(-0.554F), 0);
Assert.assertEquals(-0.56F, NumberUtils.round(-0.556F), 0);
Assert.assertEquals(-0.12F, NumberUtils.round(-0.1234F), 0);
Assert.assertEquals(-0.12F, NumberUtils.round(-0.123456789F), 0);
Assert.assertEquals(-0.13F, NumberUtils.round(-0.129F), 0);
Assert.assertEquals(-99.99F, NumberUtils.round(-99.99F), 0);
Assert.assertEquals(-100.00F, NumberUtils.round(-99.999F), 0);
Assert.assertEquals(-100.00F, NumberUtils.round(-99.9999F), 0);
}
One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).
Try this
SomeUtils.java
public static void showKeyboard(Activity activity, boolean show) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); if(show) inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); else inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0); }
You can change the comment character to something besides # like this:
git config --global core.commentchar "@"
Instead:
public class PhotosFragment extends Fragment
You can use:
public class PhotosFragment extends ListFragment
It change the methods
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<ListviewContactItem> listContact = GetlistContact();
setAdapter(new ListviewContactAdapter(getActivity(), listContact));
}
onActivityCreated is void and you didn't need to return a view like in onCreateView
You can see an example here
May 2018 react-native version 0.55.2
secureTextEntry={true} works
password={true} does not work
You can also do:
tree | grep filename
This pipes the output of the tree command to grep for a search. This will only tell you whether the file exists though.
To delete multiple rows in datagrid, c#
parts of my code:
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in datagrid1.SelectedRows)
{
//get key
int rowId = Convert.ToInt32(row.Cells[0].Value);
//avoid updating the last empty row in datagrid
if (rowId > 0)
{
//delete
aController.Delete(rowId);
//refresh datagrid
datagrid1.Rows.RemoveAt(row.Index);
}
}
}
public void Delete(int rowId)
{
var toBeDeleted = db.table1.First(c => c.Id == rowId);
db.table1.DeleteObject(toBeDeleted);
db.SaveChanges();
}
Here's how you could get previous, next and all siblings (both sides):
function prevSiblings(target) {
var siblings = [], n = target;
while(n = n.previousElementSibling) siblings.push(n);
return siblings;
}
function nextSiblings(target) {
var siblings = [], n = target;
while(n = n.nextElementSibling) siblings.push(n);
return siblings;
}
function siblings(target) {
var prev = prevSiblings(target) || [],
next = nexSiblings(target) || [];
return prev.concat(next);
}
If you think about the performace ,may be you can use "PERFORM" in a function just like this:
PERFORM 1 FROM skytf.test_2 WHERE id=i LIMIT 1;
IF FOUND THEN
RAISE NOTICE ' found record id=%', i;
ELSE
RAISE NOTICE ' not found record id=%', i;
END IF;
In many environments (e.g. Heroku), and as a convention, you can set the environment variable PORT
to tell your web server what port to listen on.
So process.env.PORT || 3000
means: whatever is in the environment variable PORT, or 3000 if there's nothing there.
So you pass that to app.listen
, or to app.set('port', ...)
, and that makes your server able to accept a "what port to listen on" parameter from the environment.
If you pass 3000
hard-coded to app.listen()
, you're always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you're running your server.