I had this error and I found that the name of one of my connection strings was wrong. Check the names as well as the actual string.
Always check for Inner Exception if any. In my case Inner Exception turned out to be really helpful in figuring out the issue.
My site was working fine in Dev Environment. But after i deployed to production, it started giving out this exception, but the Inner Exception was saying that Login failed for the particular user.
So i figured out it was something to do with the connection itself. Hence tried logging in using SSMS and even that failed.
Eventually figured out that exception showed up for the simple reason that the SQL server had only Windows Authentication enabled and SQL Authentication was failing which was what i was using for Authentication.
In short, changing Authentication to Mixed(SQL and Windows), fixed the issue for me. :)
In my case I got this message because there's a special char (&) in my connectionstring, remove it then everything's good.
Cheers
Use <packages xmlns="urn:packages">
in the place of <packages>
Just use \" instead ", it should resolve the issue.
If you are using DbContext
and EF v6+, alternatively you can use:
this.context.Database.CommandTimeout = 180;
Silverlight applications do not have direct access to machine.config.
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
I found the problem was that I had the server path within the connection string in one of these variants:
SERVER\SQLEXPRESS
SERVER
When really I should have:
.\SQLEXPRESS
For some reason I got the error whenever it had difficulty locating the instance of SQL.
The configuration manager of web configuration (web.config) is obsolete. So see this https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.appsettings?redirectedfrom=MSDN&view=dotnet-plat-ext-3.1#System_Configuration_ConfigurationManager_AppSettings
create a instance of settings
var appSettings = ConfigurationManager.AppSettings;
It might just be a connection string error, which is solved by the above process, but if you are using the dll's in multiple projects then making sure the connection string is named properly will fix the error for sure.
You could use table
:
R> x <- read.table(textConnection('
Believe Age Gender Presents Behaviour
1 FALSE 9 male 25 naughty
2 TRUE 5 male 20 nice
3 TRUE 4 female 30 nice
4 TRUE 4 male 34 naughty'
), header=TRUE)
R> table(x$Believe)
FALSE TRUE
1 3
You can not "attach" a SASS/SCSS file to an HTML document.
SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.
There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.
It's as simple as adding 2 lines of code to your HTML file.
<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>
//This is an example code to show Image Icon in TextInput//
import React, { Component } from 'react';
//import react in our code.
import { StyleSheet, View, TextInput, Image } from 'react-native';
//import all the components we are going to use.
export default class App extends Component<{}> {
render() {
return (
<View style={styles.container}>
<View style={styles.SectionStyle}>
<Image
//We are showing the Image from online
source={{uri:'http://aboutreact.com/wp-content/uploads/2018/08/user.png',}}
//You can also show the image from you project directory like below
//source={require('./Images/user.png')}
//Image Style
style={styles.ImageStyle}
/>
<TextInput
style={{ flex: 1 }}
placeholder="Enter Your Name Here"
underlineColorAndroid="transparent"
/>
</View>
<View style={styles.SectionStyle}>
<Image
//We are showing the Image from online
source={{uri:'http://aboutreact.com/wp-content/uploads/2018/08/phone.png',}}
//You can also show the image from you project directory like below
//source={require('./Images/phone.png')}
//Image Style
style={styles.ImageStyle}
/>
<TextInput
style={{ flex: 1 }}
placeholder="Enter Your Mobile No Here"
underlineColorAndroid="transparent"
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
margin: 10,
},
SectionStyle: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
borderWidth: 0.5,
borderColor: '#000',
height: 40,
borderRadius: 5,
margin: 10,
},
ImageStyle: {
padding: 10,
margin: 5,
height: 25,
width: 25,
resizeMode: 'stretch',
alignItems: 'center',
},
});
From Spring Documentation:
The
@Repository
annotation is a marker for any class that fulfils the role or stereotype of a repository (also known as Data Access Object or DAO). Among the uses of this marker is the automatic translation of exceptions, as described in Exception Translation.Spring provides further stereotype annotations:
@Component
,@Service
, and@Controller
.@Component
is a generic stereotype for any Spring-managed component.@Repository
,@Service
, and@Controller
are specializations of@Component
for more specific use cases (in the persistence, service, and presentation layers, respectively). Therefore, you can annotate your component classes with@Component
, but, by annotating them with@Repository
,@Service
, or@Controller
instead, your classes are more properly suited for processing by tools or associating with aspects.For example, these stereotype annotations make ideal targets for pointcuts.
@Repository
,@Service
, and@Controller
can also carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using@Component
or@Service
for your service layer,@Service
is clearly the better choice. Similarly, as stated earlier,@Repository
is already supported as a marker for automatic exception translation in your persistence layer.
Annotation | Meaning |
---|---|
@Component |
generic stereotype for any Spring-managed component |
@Repository |
stereotype for persistence layer |
@Service |
stereotype for service layer |
@Controller |
stereotype for presentation layer (spring-mvc) |
If you're wondering about functionality, then jQuery's .html()
performs the same intended functionality as .innerHTML
, but it also performs checks for cross-browser compatibility.
For this reason, you can always use jQuery's .html()
instead of .innerHTML
where possible.
The jQuery UI sortable plugin provides drag-and-drop reordering. A save button can extract the IDs of each item to create a comma-delimited string of those IDs, added to a hidden textbox. The textbox is returned to the server using an async postback.
This fiddle example reorders table elements, but does not save them to a database.
The sortable plugin takes one line of code to turn any list into a sortable list. If you care to use them, it also provides CSS and images to provide a visual impact to sortable list (see the example that I linked to). Developers, however, must provide code to retrieve items in their new order. I embed unique IDs of each item in the list as an HTML attribute and then retrieve those IDs via jQuery.
For example:
// ----- code executed when the document loads
$(function() {
wireReorderList();
});
function wireReorderList() {
$("#reorderExampleItems").sortable();
$("#reorderExampleItems").disableSelection();
}
function saveOrderClick() {
// ----- Retrieve the li items inside our sortable list
var items = $("#reorderExampleItems li");
var linkIDs = [items.size()];
var index = 0;
// ----- Iterate through each li, extracting the ID embedded as an attribute
items.each(
function(intIndex) {
linkIDs[index] = $(this).attr("ExampleItemID");
index++;
});
$get("<%=txtExampleItemsOrder.ClientID %>").value = linkIDs.join(",");
}
select into
is used in pl/sql to set a variable to field values. Instead, use
create table new_table as select * from old_table
But even when I import os, I am not able to call it path.basename. Is it possible to call it as directly as basename?
import os
, and then use os.path.basename
import
ing os
doesn't mean you can use os.foo
without referring to os
.
If order matters, you should keep a property on the "T" objects in your list that denotes sequence. In order to swap them, just swap the value of that property, and then use that in the .Sort(comparison with sequence property)
Hi to use the thread pool in Python you can use this library :
from multiprocessing.dummy import Pool as ThreadPool
and then for use, this library do like that :
pool = ThreadPool(threads)
results = pool.map(service, tasks)
pool.close()
pool.join()
return results
The threads are the number of threads that you want and tasks are a list of task that most map to the service.
One easy way is to drag and drop. It will copy files to /sdcard/Download. You can copy whole folders or multiple files. Make sure that "Enable Clipboard Sharing" is enabled. (under ...->Settings)
This function will determine the needed precision from the multiplication of two floating point numbers and return a result with the appropriate precision. Elegant though it is not.
function multFloats(a,b){
var atens = Math.pow(10,String(a).length - String(a).indexOf('.') - 1),
btens = Math.pow(10,String(b).length - String(b).indexOf('.') - 1);
return (a * atens) * (b * btens) / (atens * btens);
}
list comprehension could be an interesting approach as well.
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
index = np.array([2, 3, 6]) #index is changed to an array.
out = [val for i, val in enumerate(a) if all(i != index)]
>>> [1, 2, 5, 6, 8, 9]
Instead of a size divisor of 1024 * 1024
you could use the <<
bitwise shifting operator, i.e. 1<<20
to get megabytes, 1<<30
to get gigabytes, etc.
In the simplest scenario you can have e.g. a constant MBFACTOR = float(1<<20)
which can then be used with bytes, i.e.: megas = size_in_bytes/MBFACTOR
.
Megabytes are usually all that you need, or otherwise something like this can be used:
# bytes pretty-printing
UNITS_MAPPING = [
(1<<50, ' PB'),
(1<<40, ' TB'),
(1<<30, ' GB'),
(1<<20, ' MB'),
(1<<10, ' KB'),
(1, (' byte', ' bytes')),
]
def pretty_size(bytes, units=UNITS_MAPPING):
"""Get human-readable file sizes.
simplified version of https://pypi.python.org/pypi/hurry.filesize/
"""
for factor, suffix in units:
if bytes >= factor:
break
amount = int(bytes / factor)
if isinstance(suffix, tuple):
singular, multiple = suffix
if amount == 1:
suffix = singular
else:
suffix = multiple
return str(amount) + suffix
print(pretty_size(1))
print(pretty_size(42))
print(pretty_size(4096))
print(pretty_size(238048577))
print(pretty_size(334073741824))
print(pretty_size(96995116277763))
print(pretty_size(3125899904842624))
## [Out] ###########################
1 byte
42 bytes
4 KB
227 MB
311 GB
88 TB
2 PB
I tried every trick but nothing seemed to work and just resulted in hiding the text with the CSS color property to #fff since my background was #fff. Here is the code :
<input class="form-control upload_profile_pic"
type="file"
name="userfile" class="form-control"
style="color: #fff;">
or
input.form-control.upload_profile_pic {
color: #fff;
}
ApplicationContextAware Interface ,the current application context, through which you can invoke the spring container services. We can get current applicationContext instance injected by below method in the class
public void setApplicationContext(ApplicationContext context) throws BeansException.
Your problem is that you're converting the button into an HTML snippet when you add it to the table, but that snippet is not the same object as the one that has the click handler on it.
$("#myButton").click(function () {
var test = $('<button>Test</button>').click(function () {
alert('hi');
});
$("#nodeAttributeHeader").css('display', 'table-row'); // NB: changed
var tr = $('<tr>').insertBefore('#addNodeTable tr:last');
var td = $('<td>').append(test).appendTo(tr);
});
NSURL *url= [NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"userId=2323";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
Can use getSupportActionBar()
instead of getActionBar()
method.
If you're talking about git status
not showing the renames, try git commit --dry-run -a
instead
Since your config file is a normal text file, just read it using the open
function:
file = open("abc.txt", 'r')
content = file.read()
paths = content.split("\n") #split it into lines
for path in paths:
print path.split(" = ")[1]
This will print your paths. You can also store them using dictionaries or lists.
path_list = []
path_dict = {}
for path in paths:
p = path.split(" = ")
path_list.append(p)[1]
path_dict[p[0]] = p[1]
More on reading/writing file here. Hope this helps!
You don't need negative lookahead. There is working example:
/([\s\S]*?)(red|green|blue|)/g
Description:
[\s\S]
- match any character*
- match from 0 to unlimited from previous group?
- match as less as possible(red|green|blue|)
- match one of this words or nothingg
- repeat patternExample:
whiteredwhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredwhiteredwhiteredwhiteredwhiteredwhiteredgreenbluewhiteredwhiteredwhiteredwhiteredwhiteredredgreenredgreenredgreenredgreenredgreenbluewhiteredbluewhiteredbluewhiteredbluewhiteredbluewhiteredwhite
Will be:
whitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhite
Test it: regex101.com
Add the following code to the .htaccess file:
Options +SymLinksIfOwnerMatch
RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^ https://[your domain name]%{REQUEST_URI} [R,L]
Where [your domain name] is your website's domain name.
You can also redirect specific folders off of your domain name by replacing the last line of the code above with:
RewriteRule ^ https://[your domain name]/[directory name]%{REQUEST_URI} [R,L]
IPython intercepts those, they're called built-in magic commands, here's the list: https://ipython.org/ipython-doc/dev/interactive/magics.html
You can also create your own custom magics, https://ipython.org/ipython-doc/dev/config/custommagics.html
Your timeit
is here https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit
In PowerShell Core v6 (works on macOS, Linux and Windows):
[Environment]::MachineName
For current Android application package:
public String getDataDir(Context context) throws Exception {
return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.dataDir;
}
For any package:
public String getAnyDataDir(Context context, String packageName) throws Exception {
return context.getPackageManager().getPackageInfo(packageName, 0).applicationInfo.dataDir;
}
Move doSomething
definition outside of its class declaration and after B
and also make add
accessible to A
by public
-ing it or friend
-ing it.
class B;
class A
{
void doSomething(B * b);
};
class B
{
public:
void add() {}
};
void A::doSomething(B * b)
{
b->add();
}
If you would like to redirect the user after the alert, do this:
echo ("<script LANGUAGE='JavaScript'>
window.alert('Succesfully Updated');
window.location.href='<URL to redirect to>';
</script>");
But now it is not working and I contacted our hosting team then they told me to use smtp
Newsflash - it was using SMTP before. They've not provided you with the information you need to solve the problem - or you've not relayed it accurately here.
Its possible that they've disabled the local MTA on the webserver, in which case you'll need to connect the SMTP port on a remote machine. There are lots of toolkits which will do the heavy lifting for you. Personally I like phpmailer because it adds other functionality.
Certainly if they've taken away a facility which was there before and your paying for a service then your provider should be giving you better support than that (there are also lots of programs to drop in in place of a full MTA which would do the job).
C.
np.where
function works as follows:
df['X'] = np.where(df['Y']>=50, 'yes', 'no')
In your case you would want:
import numpy as np
df['my_channel'] = np.where(df.my_channel > 20000, 0, df.my_channel)
MSDN:
There is a very low probability that the value of the new Guid is all zeroes or equal to any other Guid.
Ensure that your system PATH environment variable contains the directory in which PHP is installed. Stop the Apache server and restart it once more. With luck CURL will start working.
var wrapper = $(document.body);
strings = [
"19 51 2.108997",
"20 47 2.1089"
];
$.each(strings, function(key, value) {
var tmp = value.split(" ");
$.each([
tmp[0] + " " + tmp[1],
tmp[2]
], function(key, value) {
$("<span>" + value + "</span>").appendTo(wrapper);
});
});
Try opening a new command prompt as an administrator. This worked for me on Windows 10. (I know this is an old answer, but I had to share this because having to write a VBS script just for this is absurd).
You have two possibilities (for an IPv4 address) :
varchar(15)
, if your want to store the IP address as a string
192.128.0.15
for instanceinteger
(4 bytes), if you convert the IP address to an integer
3229614095
for the IP I used before
The second solution will require less space in the database, and is probably a better choice, even if it implies a bit of manipulations when storing and retrieving the data (converting it from/to a string).
About those manipulations, see the ip2long()
and long2ip()
functions, on the PHP-side, or inet_aton()
and inet_ntoa()
on the MySQL-side.
per @Kevin-Reid's answer, here's an alternative to the "I ended up doing the following" example that avoids needing to name and then lookup the form object again by constructing the form specifically (using jQuery)..
var url = 'http://example.com/vote/' + Username;
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="api_url" value="' + Return_URL + '" />' +
'</form>');
$('body').append(form);
form.submit();
Note that -p
is an argument to the mkdir
command specifically, not the whole of Unix. Every command can have whatever arguments it needs.
In this case it means "parents", meaning mkdir
will create a directory and any parents that don't already exist.
Personally I would go with:
DataTable tbl = Gridview1.DataSource as DataTable;
This would allow you to test for null as this results in either DataTable object or null. Casting it as a DataTable using (DataTable)Gridview1.DataSource would cause a crashing error in case the DataSource is actually a DataSet or even some kind of collection.
Supporting Documentation: MSDN Documentation on "as"
set the function options(max.print=10000) in top of your program. since you want intialize this before it works. It is working for me.
For now i think best emulator is https://app.crossbrowsertesting.com
It has real sizes and virtual keyboard (that is the most important thing) , zooming events...
Also https://appetize.io/demo has same things but it has time limit.
You cannot do this:
vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);
in a class outside of a method.
You can initialize the data members at the point of declaration, but not with ()
brackets:
class Foo {
vector<string> name = vector<string>(5);
vector<int> val{vector<int>(5,0)};
};
Before C++11, you need to declare them first, then initialize them e.g in a contructor
class Foo {
vector<string> name;
vector<int> val;
public:
Foo() : name(5), val(5,0) {}
};
It is possible to scaffold a view. Just use -Tables the way you would to scaffold a table, only use the name of your view. E.g., If the name of your view is ‘vw_inventory’, then run this command in the Package Manager Console (substituting your own information for "My..."):
PM> Scaffold-DbContext "Server=MyServer;Database=MyDatabase;user id=MyUserId;password=MyPassword" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Temp -Tables vw_inventory
This command will create a model file and context file in the Temp directory of your project. You can move the model file into your models directory (remember to change the namespace name). You can copy what you need from the context file and paste it into the appropriate existing context file in your project.
Note: If you want to use your view in an integration test using a local db, you'll need to create the view as part of your db setup. If you’re going to use the view in more than one test, make sure to add a check for existence of the view. In this case, since the SQL ‘Create View’ statement is required to be the only statement in the batch, you’ll need to run the create view as dynamic Sql within the existence check statement. Alternatively you could run separate ‘if exists drop view…’, then ‘create view’ statements, but if multiple tests are running concurrently, you don’t want the view to be dropped if another test is using it. Example:
void setupDb() {
...
SomeDb.Command(db => db.Database.ExecuteSqlRaw(CreateInventoryView()));
...
}
public string CreateInventoryView() => @"
IF OBJECT_ID('[dbo].[vw_inventory]') IS NULL
BEGIN EXEC('CREATE VIEW [dbo].[vw_inventory] AS
SELECT ...')
END";
You can split the string into characters and filter it.
<?php
function filter_alphanum($string) {
$characters = str_split($string);
$alphaNumeric = array_filter($characters,"ctype_alnum");
return join($alphaNumeric);
}
$res = filter_alphanum("a!bc!#123");
print_r($res); // abc123
?>
In case you missed the configuration at the Project Structure(File -> Project Structure), just reconfigure it like below:
Enjoy coding J
You could use CSS for this and create classes for the elements. So you'd have something like this
p.detail { color:#4C4C4C;font-weight:bold;font-family:Calibri;font-size:20 }
span.name { color:#FF0000;font-weight:bold;font-family:Tahoma;font-size:20 }
Then your HTML would read:
<p class="detail">My Name is: <span class="name">Tintinecute</span> </p>
It's a lot neater then inline stylesheets, is easier to maintain and provides greater reuse.
Here's the complete HTML to demonstrate what I mean:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<style type="text/css">
p.detail { color:#4C4C4C;font-weight:bold;font-family:Calibri;font-size:20 }
span.name { color:#FF0000;font-weight:bold;font-family:Tahoma;font-size:20 }
</style>
</head>
<body>
<p class="detail">My Name is: <span class="name">Tintinecute</span> </p>
</body>
</html>
You'll see that I have the stylesheet classes in a style tag in the header, and then I only apply those classes in the code such as <p class="detail"> ... </p>
. Go through the w3schools tutorial, it will only take a couple of hours and will really turn you around when it comes to styling your HTML elements. If you cut and paste that into an HTML document you can edit the styles and see what effect they have when you open the file in a browser. Experimenting like this is a great way to learn.
SELECT * INTO [table_a] FROM dbo.myView
I prefer to use border-spacing
as it allows more flexibility. For instance, you could do
table {
border-spacing: 0 2px;
}
Which would only collapse the vertical borders and leave the horizontal ones in tact, which is what it sounds like the OP was actually looking for.
Note that border-spacing: 0
is not the same as border-collapse: collapse
. You will need to use the latter if you want to add your own border to a tr
as seen here.
At FirstScreen.java
Intent intent = new Intent(FirstScreen.this, SecondScreen.class);
String keyIdentifier = null;
intent.putExtra(strName, keyIdentifier);
At SecondScreen.java
String keyIdentifier;
if (savedInstanceState != null)
keyIdentifier= (String) savedInstanceState.getSerializable(strName);
else
keyIdentifier = getIntent().getExtras().getString(strName);
A couple of examples:
infix fun Double.f(fmt: String) = "%$fmt".format(this)
infix fun Double.f(fmt: Float) = "%${if (fmt < 1) fmt + 1 else fmt}f".format(this)
val pi = 3.14159265358979323
println("""pi = ${pi f ".2f"}""")
println("pi = ${pi f .2f}")
First Off, I object to this other question regarding Visual Studio 2015 as a duplicate question. How do I open SSRS (.rptproj) and SSIS (.dtproj) files in Visual Studio 2015? [duplicate]
Basically this question has the title ...Visual Studio 2012 / 2013
What about ALL the improvements and changes to VS 2015 ??? SSDT has been updated and changed. The entire way of doing various additions and updates is different.
So having vented / rant - I did open a VS 2015 update 2 instance and proceeded to open an existing solution that include a .rptproj
project. Now this computer does not yet have sql server installed on it yet.
Solution for ME : Tools --> Extension and Updates --> Updates --> sql server tooling updates
Click on Update button and wait a long time and SSDT then installs and close visual studio 2015 and re-open and it works for me.
In case it is NOT found in VS 2015 for some reason : scroll to the bottom, pick your language iso https://msdn.microsoft.com/en-us/mt186501.aspx?f=255&MSPPError=-2147217396
Use find
with a wildcard:
find . -name 'mystring*'
You can open PowerShell and type "python". After Python has been imported, you can copy paste the source code from your favourite text-editor to run the code.
The window won't close.
You can use the statement :-
Class c = s.getClass();
To get the class instance.
You have to surround the select part with parenthesis.
CREATE TABLE SCHEMA.NEW_TB AS (
SELECT *
FROM SCHEMA.OLD_TB
) WITH NO DATA
Should work. Pay attention to all the things @Gilbert said would not be copied.
I'm assuming DB2 on Linux/Unix/Windows here, since you say DB2 v9.5.
In 2018 Mozilla warns us in the Mozilla Docs here!
I quote "Logging Objects":
Don't use
console.log(obj);
, useconsole.log(JSON.parse(JSON.stringify(obj)));
.This way you are sure you are seeing the value of obj at the moment you log it.
You can also use "or" operator,
for( int i = 0 ; i < 100 || someOtherCondition() ; i++ ) {
...
}
Use cursor.lastrowid
to get the last row ID inserted on the cursor object, or connection.insert_id()
to get the ID from the last insert on that connection.
It's caused by n % x
where x = 0
in the first loop iteration. You can't calculate a modulus with respect to 0.
Another silly mistake you can do is copy recursive function from non class environment to class and don`t change inner self calls to $this->method_name()
i`m writing this because couldn`t understand why i got this error and this thread is first in google when you search for this error.
First of all, create a Github account and project in Github. Go to the root folder and follow steps.
The most important thing we forgot here is ignoring the file. Every time we run Gradle or build it creates new files that are changeable from build to build and pc to pc. We do not want all the files from Android Studio to be added to Git. Files like generated code, binary files (executables) should not be added to Git (version control). So please use .gitignore file while uploading projects to Github. It also reduces the size of the project uploaded to the server.
git init
Create .gitignore txt file in root folder. Place these content in the file. (this step not required if the file is auto-generated)
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.idea
.DS_Store
/build
/captures
.externalNativeBuild
git add .
git remote add origin https://github.com/username/project.git
git commit - m "My First Commit"
git push -u origin master
Note : As per suggestion from different developers, they always suggest to use git from the command line. It is up to you.
You can do this by wrapping the page contents in a div with the following id styling applied:
<style>
#wrap {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -60px;
}
</style>
<div id="wrap">
<!-- Your page content here... -->
</div>
Worked for me.
as.character()
would be the general way rather than use paste()
for its side effect
> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"
(I presume this is a simple example and something like this:
v <- "20081101"
isn't possible?)
The function below is a part of string processing library I am maintaining on Github. It removes and unwanted characters from a string, exactly what you want
int zstring_search_chr(const char *token,char s){
if (!token || s=='\0')
return 0;
for (;*token; token++)
if (*token == s)
return 1;
return 0;
}
char *zstring_remove_chr(char *str,const char *bad) {
char *src = str , *dst = str;
while(*src)
if(zstring_search_chr(bad,*src))
src++;
else
*dst++ = *src++; /* assign first, then incement */
*dst='\0';
return str;
}
An example usage could be
Example Usage
char s[]="this is a trial string to test the function.";
char const *d=" .";
printf("%s\n",zstring_remove_chr(s,d));
Example Output
thisisatrialstringtotestthefunction
You may want to check other available functions, or even contribute to the project :) https://github.com/fnoyanisi/zString
For Windows Users,
Use the Tomcat Service Installer from the Apache tomcat downloads page. You will get a .exe file. which Installs the service for windows. It will usually install Apache tomcat at "C:\Program Files\Apache Software Foundation\Tomcat 8.0" and its easily recognized in eclipse.
Use /config.php
.
Well actually...
I wouldn't have the Fragment try to finish the Activity. That places too much authority on the Fragment in my opinion. Instead, I would use the guide here: http://developer.android.com/training/basics/fragments/communicating.html
Have the Fragment define an interface which the Activity must implement. Make a call up to the Activity, then let the Activity decide what to do with the information. If the activity wishes to finish itself, then it can.
What you said above is correct. Sometimes final methods are created as inline, but there is no other way to explicitly create an inline function in java.
You can also take this easier way.
W1 = tf.Variable(tf.truncated_normal([6, 6, 1, K], stddev=0.1), name="W1")
B1 = tf.Variable(tf.constant(0.1, tf.float32, [K]), name="B1")
Similarly, W2, B2, W3, .....
Saver
and save itmodel_saver = tf.train.Saver()
# Train the model and save it in the end
model_saver.save(session, "saved_models/CNN_New.ckpt")
with tf.Session(graph=graph_cnn) as session:
model_saver.restore(session, "saved_models/CNN_New.ckpt")
print("Model restored.")
print('Initialized')
W1 = session.run(W1)
print(W1)
While running in different python instance, use
with tf.Session() as sess:
# Restore latest checkpoint
saver.restore(sess, tf.train.latest_checkpoint('saved_model/.'))
# Initalize the variables
sess.run(tf.global_variables_initializer())
# Get default graph (supply your custom graph if you have one)
graph = tf.get_default_graph()
# It will give tensor object
W1 = graph.get_tensor_by_name('W1:0')
# To get the value (numpy array)
W1_value = session.run(W1)
The better solution is to simply move the position of the viewport based on the change in the zoom. The zoom point is simply the point in the old zoom and the new zoom that you want to remain the same. Which is to say the viewport pre-zoomed and the viewport post-zoomed have the same zoompoint relative to the viewport. Given that we're scaling relative to the origin. You can adjust the viewport position accordingly:
scalechange = newscale - oldscale;
offsetX = -(zoomPointX * scalechange);
offsetY = -(zoomPointY * scalechange);
So really you can just pan over down and to the right when you zoom in, by a factor of how much you zoomed in, relative to the point you zoomed at.
@IBAction func back(_ sender: Any) {
self.dismiss(animated: false, completion: nil)
}
[-a-z0-9]+,[a-z0-9-]+,[a-z-0-9]+ and also [a-z-0-9]+ all are same.The hyphen between two ranges considered as a symbol.And also [a-z0-9-+()]+ this regex allow hyphen.
I've got a YouTube video on this.
Short answer: Use mock
when you're passing in the thing that you want mocked, and patch
if you're not. Of the two, mock is strongly preferred because it means you're writing code with proper dependency injection.
Silly example:
# Use a mock to test this.
my_custom_tweeter(twitter_api, sentence):
sentence.replace('cks','x') # We're cool and hip.
twitter_api.send(sentence)
# Use a patch to mock out twitter_api. You have to patch the Twitter() module/class
# and have it return a mock. Much uglier, but sometimes necessary.
my_badly_written_tweeter(sentence):
twitter_api = Twitter(user="XXX", password="YYY")
sentence.replace('cks','x')
twitter_api.send(sentence)
fopen() is a C library function and so you won't see any syscall instructions in your code, just a regular function call. At some point, it does call open(2), but it does that via a trampoline. There is simply a jump to the VDSO page, which is provided by the kernel to every process. The VDSO then provides code to make the system call. On modern processors, the SYSCALL or SYSENTER instructions will be used, but you can also use INT 80h on x86 processors.
you can use SpinUntil which is buildin in the .net-framework. Please note: This method causes high cpu-workload.
When using batch insert use the following syntax:
INSERT INTO TABLE (id, name, age) VALUES (1, "A", 19), (2, "B", 17), (3, "C", 22)
ON DUPLICATE KEY UPDATE
name = VALUES (name),
...
I think df['word'].value_counts()
should serve. By skipping the groupby machinery, you'll save some time. I'm not sure why count
should be much slower than max
. Both take some time to avoid missing values. (Compare with size
.)
In any case, value_counts has been specifically optimized to handle object type, like your words, so I doubt you'll do much better than that.
Encountered similar problem: parsing CSV file with special characters like é, è, ö etc ...
The following worked fine for me:
To represent the characters correctly on the html page, the header was needed :
header('Content-Type: text/html; charset=UTF-8');
In order to parse every character correctly, I used:
utf8_encode(fgets($file));
Dont forget to use in all following string operations the 'Multibyte String Functions', like:
mb_strtolower($value, 'UTF-8');
Your problem is those pernicious double quotes.
SQL> CREATE TABLE "APC"."PS_TBL_DEPARTMENT_DETAILS"
2 (
3 "Company Code" VARCHAR2(255),
4 "Company Name" VARCHAR2(255),
5 "Sector_Code" VARCHAR2(255),
6 "Sector_Name" VARCHAR2(255),
7 "Business_Unit_Code" VARCHAR2(255),
8 "Business_Unit_Name" VARCHAR2(255),
9 "Department_Code" VARCHAR2(255),
10 "Department_Name" VARCHAR2(255),
11 "HR_ORG_ID" VARCHAR2(255),
12 "HR_ORG_Name" VARCHAR2(255),
13 "Cost_Center_Number" VARCHAR2(255),
14 " " VARCHAR2(255)
15 )
16 /
Table created.
SQL>
Oracle SQL allows us to ignore the case of database object names provided we either create them with names all in upper case, or without using double quotes. If we use mixed case or lower case in the script and wrapped the identifiers in double quotes we are condemned to using double quotes and the precise case whenever we refer to the object or its attributes:
SQL> select count(*) from PS_TBL_DEPARTMENT_DETAILS
2 where Department_Code = 'BAH'
3 /
where Department_Code = 'BAH'
*
ERROR at line 2:
ORA-00904: "DEPARTMENT_CODE": invalid identifier
SQL> select count(*) from PS_TBL_DEPARTMENT_DETAILS
2 where "Department_Code" = 'BAH'
3 /
COUNT(*)
----------
0
SQL>
tl;dr
don't use double quotes in DDL scripts
(I know most third party code generators do, but they are disciplined enough to put all their object names in UPPER CASE.)
The reverse is also true. If we create the table without using double-quotes …
create table PS_TBL_DEPARTMENT_DETAILS
( company_code VARCHAR2(255),
company_name VARCHAR2(255),
Cost_Center_Number VARCHAR2(255))
;
… we can reference it and its columns in whatever case takes our fancy:
select * from ps_tbl_department_details
… or
select * from PS_TBL_DEPARTMENT_DETAILS;
… or
select * from PS_Tbl_Department_Details
where COMAPNY_CODE = 'ORCL'
and cost_center_number = '0980'
You can do:
var buf = Buffer.from(bufStr, 'utf8');
But this is a bit silly, so another suggestion would be to copy the minimal amount of code out of the called function to allow yourself access to the original buffer. This might be quite easy or fairly difficult depending on the details of that library.
Below mentioned link gives the clear explanation with example.
http://www.aspsnippets.com/Articles/Open-Show-jQuery-UI-Dialog-Modal-Popup-on-Button-Click.aspx
Code from the same link
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("#dialog").dialog({
modal: true,
autoOpen: false,
title: "jQuery Dialog",
width: 300,
height: 150
});
$("#btnShow").click(function () {
$('#dialog').dialog('open');
});
});
</script>
<input type="button" id="btnShow" value="Show Popup" />
<div id="dialog" style="display: none" align = "center">
This is a jQuery Dialog.
</div>
If its an OrderedDict()
you can easily access the elements by indexing by getting the tuples of (key,value) pairs as follows
>>> import collections
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> d.items()
[('foo', 'python'), ('bar', 'spam')]
>>> d.items()[0]
('foo', 'python')
>>> d.items()[1]
('bar', 'spam')
Note for Python 3.X
dict.items
would return an iterable dict view object rather than a list. We need to wrap the call onto a list in order to make the indexing possible
>>> items = list(d.items())
>>> items
[('foo', 'python'), ('bar', 'spam')]
>>> items[0]
('foo', 'python')
>>> items[1]
('bar', 'spam')
This is because, in C#, single quotes (''
) denote (or encapsulate) a single character, whereas double quotes (""
) are used for a string of characters. For example:
var myChar = '=';
var myString = "==";
You can convert Map
to JSON
using Jackson
as follows:
Map<String,Object> map = new HashMap<>();
//You can convert any Object.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
map.put("key3","string1");
map.put("key4","string2");
String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);
Maven Dependencies for Jackson
:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
If you are using JSONObject
library, you can convert map to JSON
as follows:
Map<String, Object> map = new HashMap<>();
// Convert a map having list of values.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
JSONObject json = new JSONObject(map);
System.out.println(json);
Maven Dependencies for JSONObject
:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
Hope this will help. Happy coding.
If you have 2 arrays need to be merged based on values even its in different order
let arr1 = [
{ id:"1", value:"this", other: "that" },
{ id:"2", value:"this", other: "that" }
];
let arr2 = [
{ id:"2", key:"val2"},
{ id:"1", key:"val1"}
];
you can do like this
const result = arr1.map(item => {
const obj = arr2.find(o => o.id === item.id);
return { ...item, ...obj };
});
console.log(result);
Following will give you active connections/ queries in postgres DB-
SELECT
pid
,datname
,usename
,application_name
,client_hostname
,client_port
,backend_start
,query_start
,query
,state
FROM pg_stat_activity
WHERE state = 'active';
You may use 'idle' instead of active to get already executed connections/queries.
I was able to write a general contains
function for std::list
and std::vector
,
template<typename T>
bool contains( const list<T>& container, const T& elt )
{
return find( container.begin(), container.end(), elt ) != container.end() ;
}
template<typename T>
bool contains( const vector<T>& container, const T& elt )
{
return find( container.begin(), container.end(), elt ) != container.end() ;
}
// use:
if( contains( yourList, itemInList ) ) // then do something
This cleans up the syntax a bit.
But I could not use template template parameter magic to make this work arbitrary stl containers.
// NOT WORKING:
template<template<class> class STLContainer, class T>
bool contains( STLContainer<T> container, T elt )
{
return find( container.begin(), container.end(), elt ) != container.end() ;
}
Any comments about improving the last answer would be nice.
Try:
select * from information_schema.tables
See: http://dev.mysql.com/doc/refman/5.0/en/information-schema.html
In the latest Mac OS You can use shift
+ home
or shift
+ end
add CSS or class to the input element which works in select and text tags like
style="pointer-events: none;background-color:#E9ECEF"
Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)
To quote the most relevant bits:
[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.
The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”
Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.
The full post explains this in more detail. At RTM, the MSDN docs on this should be better.
You must build an executable file before you can run it. So if you don't “BUILD” your file, then it will not be able to link and load that object file, and hence it does not have the required binary numbers to execute.
So basically right click on the Project -> Build Project -> Run As Local C/C++ Application
should do the trick
HOW TO ANIMATE OPACITY WITH CSS:
this is my code:
the CSS code
.item {
height:200px;
width:200px;
background:red;
opacity:0;
transition: opacity 1s ease-in-out;
}
.item:hover {
opacity: 1;
}
code {
background: linear-gradient(to right,#fce4ed,#ffe8cc);
}
_x000D_
<div class="item">
</div>
<p><code> move mouse over top of this text</code></p>
_x000D_
function vote(){
var vote = getElementById("yourOpinion")
if(this.workWithYou):
vote += 1 };
lol
I've found that (at Chrome 56, OSX) the favicon state appears to be cached for the browser lifetime, so if a favicon isn't being loaded, it won't be until after restarting Chrome. It appears that it doesn't show up in the "application" tab in dev tools and isn't cleared by a hard reload or 'Clear site data'.
There are several ways:
Write-Host
: Write directly to the console, not included in function/cmdlet output. Allows foreground and background colour to be set.
Write-Debug
: Write directly to the console, if $DebugPreference
set to Continue or Stop.
Write-Verbose
: Write directly to the console, if $VerbosePreference
set to Continue or Stop.
The latter is intended for extra optional information, Write-Debug
for debugging (so would seem to fit in this case).
Additional: In PSH2 (at least) scripts using cmdlet binding will automatically get the -Verbose
and -Debug
switch parameters, locally enabling Write-Verbose
and Write-Debug
(i.e. overriding the preference variables) as compiled cmdlets and providers do.
#include<iostream>
#include<stdlib>
using namespace std;
void main()
{
char ch;
int x;
cin >> ch;
x = char (ar[1]);
cout << x;
}
For me I had to settimeout in addition to @arjun-sk solution's (link), as I was getting the error
setTimeout(() => {
this.modalService.open(this.loginModal, { centered: true })
}, 100);
Try echo $'a\nb'
.
If you want to store it in a variable and then use it with the newlines intact, you will have to quote your usage correctly:
var=$'a\nb\nc'
echo "$var"
Or, to fix your example program literally:
var="a b c"
for i in $var; do
p="`echo -e "$p\\n$i"`"
done
echo "$p"
import keyboard
keyboard.press_and_release('anykey')
a bit late to the game, but I found a way to make the original syntax in this question work (I'm on Oracle 11g)
** first switch to schema of your MV **
EXECUTE DBMS_MVIEW.REFRESH(LIST=>'MV_MY_VIEW');
alternatively you can add some options:
EXECUTE DBMS_MVIEW.REFRESH(LIST=>'MV_MY_VIEW',PARALLELISM=>4);
this actually works for me, and adding parallelism option sped my execution about 2.5 times.
More info here: How to Refresh a Materialized View in Parallel
As an update to The Minister's answer, you can now do this with es2015:
function Tuple(...args) {
args.forEach((val, idx) =>
Object.defineProperty(this, "item"+idx, { get: () => val })
)
}
var t = new Tuple("a", 123)
console.log(t.item0) // "a"
t.item0 = "b"
console.log(t.item0) // "a"
You can't avoid polling, there isn't any event for href change.
Using intervals is quite light anyways if you don't go overboard. Checking the href every 50ms or so will not have any significant effect on performance if you're worried about that.
.NET XSLT implementation allows to write custom managed functions in the stylesheet. For lower-case() it can be:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:utils="urn:myExtension" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<msxsl:script implements-prefix="utils" language="C#">
<![CDATA[
public string ToLower(string stringValue)
{
string result = String.Empty;
if(!String.IsNullOrEmpty(stringValue))
{
result = stringValue.ToLower();
}
return result;
}
]]>
</msxsl:script>
<!-- using of our custom function -->
<lowercaseValue>
<xsl:value-of select="utils:ToLower($myParam)"/>
</lowercaseValue>
Assume, that can be slow, but still acceptable.
Do not forget to enable embedded scripts support for transform:
// Create the XsltSettings object with script enabled.
XsltSettings xsltSettings = new XsltSettings(false, true);
XslCompiledTransform xslt = new XslCompiledTransform();
// Load stylesheet
xslt.Load(xsltPath, xsltSettings, new XmlUrlResolver());
Use the command-line option -O0
(-[capital o][zero]) to disable optimization, and -S
to get assembly file. Look here to see more gcc command-line options.
I think this is the best way to get the month name when you have the month number
Select DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )
Or
Select DateName( month , DateAdd( month , @MonthNumber , -1 ) )
NSDate *start = [NSDate date];
// do stuff...
NSTimeInterval timeInterval = [start timeIntervalSinceNow];
timeInterval
is the difference between start and now, in seconds, with sub-millisecond precision.
Transient
Scoped
Singleton
Use Singletons where you need to maintain application wide state. Application configuration or parameters, Logging Service, caching of data is some of the examples where you can use singletons.
CPUnit (http://cpunit.sourceforge.net) is a framework that is similar to Google Test, but which relies on less macos (asserts are functions), and where the macros are prefixed to avoid the usual macro pitfall. Tests look like:
#include <cpunit>
namespace MyAssetTest {
using namespace cpunit;
CPUNIT_FUNC(MyAssetTest, test_stuff) {
int some_value = 42;
assert_equals("Wrong value!", 666, some_value);
}
// Fixtures go as follows:
CPUNIT_SET_UP(MyAssetTest) {
// Setting up suite here...
// And the same goes for tear-down.
}
}
They auto-register, so you need not more than this. Then it is just compile and run. I find using this framework very much like using JUnit, for those who have had to spend some time programming Java. Very nice!
If you want the while loop to stop after some condition, and your foo
command returns non-zero when this condition is met then you can get the loop to break like this:
while foo; do echo 'sleeping...'; sleep 5; done;
For example, if the foo
command is deleting things in batches, and it returns 1 when there is nothing left to delete.
This works well if you have a custom script that needs to run a command many times until some condition. You write the script to exit with 1
when the condition is met and exit with 0
when it should be run again.
For example, say you have a python script batch_update.py
which updates 100 rows in a database and returns 0
if there are more to update and 1
if there are no more. The the following command will allow you to update rows 100 at a time with sleeping for 5 seconds between updates:
while batch_update.py; do echo 'sleeping...'; sleep 5; done;
You can do this simply by using pandas drop duplicates function
df.drop_duplicates(['A','B'],keep= 'last')
in /etc/my.cnf
:
[mysqld]
...
performance_schema = 0
table_cache = 0
table_definition_cache = 0
max-connect-errors = 10000
query_cache_size = 0
query_cache_limit = 0
...
Good work on server with 256MB Memory.
<div runat="server">
is mapped to a HtmlGenericControl
.
Try using BtnventCss.Attributes.Add("class", "hom_but_a");
break
breaks out of a loop, not an if
statement, as others have pointed out. The motivation for this isn't too hard to see; think about code like
for item in some_iterable:
...
if break_condition():
break
The break
would be pretty useless if it terminated the if
block rather than terminated the loop -- terminating a loop conditionally is the exact thing break
is used for.
Sometimes there are source files which are missing from your target.
You can select the files that seem to be "missing" and check in the right-hand utility bar that their checkboxes are selected for the Target you are building.
I use this code piece while working with indexes for radio group:
radioGroup.check(radioGroup.getChildAt(index).getId());
If you happen to be on MacOS and checked the "save password" box in Android Studio, you can recover the password from Keychain Access.
You can also use day names like Mon
for Monday, Tue
for Tuesday, etc. It's more human friendly.
The first step would be to add
position: 'absolute',
then if you want the element full width, add
left: 0,
right: 0,
then, if you want to put the element in the bottom, add
bottom: 0,
// don't need set top: 0
if you want to position the element at the top, replace bottom: 0
by top: 0
Open res -> values -> styles.xml
and to your <style>
add this line replacing with your image path <item name="android:windowBackground">@drawable/background</item>
. Example:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowBackground">@drawable/background</item>
</style>
</resources>
There is a <item name ="android:colorBackground">@color/black</item>
also, that will affect not only your main window background but all the component in your app. Read about customize theme here.
If you want version specific styles:
If a new version of Android adds theme attributes that you want to use, you can add them to your theme while still being compatible with old versions. All you need is another styles.xml file saved in a values directory that includes the resource version qualifier. For example:
res/values/styles.xml # themes for all versions res/values-v21/styles.xml # themes for API level 21+ only
Because the styles in the values/styles.xml file are available for all versions, your themes in values-v21/styles.xml can inherit them. As such, you can avoid duplicating styles by beginning with a "base" theme and then extending it in your version-specific styles.
Stored procedure is the best way to do it. Because Meherzad's solution would work only if the data follows the same order.
If we have a table structure like this
col1 | col2 | col3
-----+------+------
3 | k | 7
5 | d | 3
1 | a | 5
6 | o | 2
2 | 0 | 8
It wont work. SQL Fiddle Demo
Here is a sample procedure code to achieve the same.
delimiter //
CREATE PROCEDURE chainReaction
(
in inputNo int
)
BEGIN
declare final_id int default NULL;
SELECT col3
INTO final_id
FROM table1
WHERE col1 = inputNo;
IF( final_id is not null) THEN
INSERT INTO results(SELECT col1, col2, col3 FROM table1 WHERE col1 = inputNo);
CALL chainReaction(final_id);
end if;
END//
delimiter ;
call chainReaction(1);
SELECT * FROM results;
DROP TABLE if exists results;
Design patterns are just tools--kind of like library functions. If you know that they are there and their approximate function, you can go dig them out of a book when needed.
There is nothing magic about design patterns, and any good programmer figured 90% of them out for themselves before any books came out. For the most part I consider the books to be most useful at simply defining names for the various patterns so we can discuss them more easily.
I had the same issue and tried various things to fix this, amending the .bash_profile file, logging in and out, without any luck. In the end, restarting my machine fixed it.
In short:
getPath()
gets the path string that the File
object was constructed with, and it may be relative current directory.getAbsolutePath()
gets the path string after resolving it against the current directory if it's relative, resulting in a fully qualified path.getCanonicalPath()
gets the path string after resolving any relative path against current directory, and removes any relative pathing (.
and ..
), and any file system links to return a path which the file system considers the canonical means to reference the file system object to which it points.Also, each of these has a File equivalent which returns the corresponding File
object.
Note that IMO, Java got the implementation of an "absolute" path wrong; it really should remove any relative path elements in an absolute path. The canonical form would then remove any FS links or junctions in the path.
First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate
$('.swipeRight').click(function()
{
$('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});
$('.swipeLeft').click(function()
{
$('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});
The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.
Your code is fine, but the problem is inside the batch file.
You have to show the content of the bat file, your problem is in the paths inside the bat file.
I could be wrong, but I thought that slashes only appeared in branch names when they related to a remote repo, for example origin/master
.
specifically I want to overload
Boolean.Parse
to allow an int argument.
Would an extension for int work?
public static bool ToBoolean(this int source){
// do it
// return it
}
Then you can call it like this:
int x = 1;
bool y = x.ToBoolean();
Here's a sample which is more efficient on long strings with many small replacements.
source = "Here is foo, it does moo!"
replacements = {
'is': 'was', # replace 'is' with 'was'
'does': 'did',
'!': '?'
}
def replace(source, replacements):
finder = re.compile("|".join(re.escape(k) for k in replacements.keys())) # matches every string we want replaced
result = []
pos = 0
while True:
match = finder.search(source, pos)
if match:
# cut off the part up until match
result.append(source[pos : match.start()])
# cut off the matched part and replace it in place
result.append(replacements[source[match.start() : match.end()]])
pos = match.end()
else:
# the rest after the last match
result.append(source[pos:])
break
return "".join(result)
print replace(source, replacements)
The point is in avoiding many concatenations of long strings. We chop the source string to fragments, replacing some of the fragments as we form the list, and then join the whole thing back into a string.
I would suggest using
v = np.diff(t)
this is simple and easy to read.
But if you want v
to have the same length as t
then
v = np.diff([t[0]] + t) # for python 3.x
or
v = np.diff(t + [t[-1]])
FYI: this will only work for lists.
for numpy arrays
v = np.diff(np.append(t[0], t))
You don't need jQuery to achieve this. In your form add:
onsubmit="return buttonSubmit(this)
or in JavaScript:
myform.setAttribute("onsubmit", "return buttonSubmit(this)");
In your buttonSubmit
function (or whatver you call it), you can submit the form using AJAX. buttonSubmit
will only get called if your form is validated in HTML5.
In case this helps anyone, here is my buttonSubmit
function:
function buttonSubmit(e)
{
var ajax;
var formData = new FormData();
for (i = 0; i < e.elements.length; i++)
{
if (e.elements[i].type == "submit")
{
if (submitvalue == e.elements[i].value)
{
submit = e.elements[i];
submit.disabled = true;
}
}
else if (e.elements[i].type == "radio")
{
if (e.elements[i].checked)
formData.append(e.elements[i].name, e.elements[i].value);
}
else
formData.append(e.elements[i].name, e.elements[i].value);
}
formData.append("javascript", "javascript");
var action = e.action;
status = action.split('/').reverse()[0] + "-status";
ajax = new XMLHttpRequest();
ajax.addEventListener("load", manageLoad, false);
ajax.addEventListener("error", manageError, false);
ajax.open("POST", action);
ajax.send(formData);
return false;
}
Some of my forms contain multiple submit buttons, hence this line if (submitvalue == e.elements[i].value)
. I set the value of submitvalue
using a click event.
the issue of too long content @beenotung can be resolved by this css class :
.col{
max-width :20% !important;
}
example fork from @jpoveda
Caveats: this answer only allows exports color settings.
iTerm => Preferences => Profiles => Colors => Load Presets => Export
Import shall be similar.
Updating with more options
list1 = ['foo', 'fob', 'faz', 'funk']
addstring = 'bar'
for index, value in enumerate(list1):
list1[index] = addstring + value #this will prepend the string
#list1[index] = value + addstring this will append the string
Avoid using keywords as variables like 'list', renamed 'list' as 'list1' instead
Sending private message through api is now possible.
Fire this event for sending message(initialization of facebook object should be done before).
to:user
id of facebook
function facebook_send_message(to) {
FB.ui({
app_id:'xxxxxxxx',
method: 'send',
name: "sdfds jj jjjsdj j j ",
link: 'https://apps.facebook.com/xxxxxxxaxsa',
to:to,
description:'sdf sdf sfddsfdd s d fsf s '
});
}
Properties
app_id
Your application's identifier. Required, but automatically specified
by most SDKs.
redirect_uri
The URL to redirect to after the user clicks the Send or Cancel
buttons on the dialog. Required, but automatically specified by most
SDKs.
display
The display mode in which to render the dialog. This is automatically
specified by most SDKs.
to
A user ID or username to which to send the message. Once the dialog
comes up, the user can specify additional users, Facebook groups, and
email addresses to which to send the message. Sending content to a
Facebook group will post it to the group's wall.
link
(required) The link to send in the message.
picture
By default a picture will be taken from the link specified. The URL
of a picture to include in the message. The picture will be shown
next to the link.
name By default a title will be taken from the link specified. The name of the link, i.e. the text to display that the user will click on.
description
By default a description will be taken from the link specified.
Descriptive text to show below the link.
See more here
@VishwaKumar:
For sending message with custom text, you have to add 'message' parameter to FB.ui
, but I think this feature is deprecated. You can't pre-fill the message anymore. Though try once.
FB.ui({
method: 'send',
to: '1234',
message: 'A request especially for one person.',
data: 'tracking information for the user'
});
See this link: http://fbdevwiki.com/wiki/FB.ui
Precision of a number is the number of digits.
Scale of a number is the number of digits after the decimal point.
What is generally implied when setting precision and scale on field definition is that they represent maximum values.
Example, a decimal field defined with precision=5
and scale=2
would allow the following values:
123.45
(p=5,s=2)12.34
(p=4,s=2)12345
(p=5,s=0)123.4
(p=4,s=1)0
(p=0,s=0)The following values are not allowed or would cause a data loss:
12.345
(p=5,s=3) => could be truncated into 12.35
(p=4,s=2)1234.56
(p=6,s=2) => could be truncated into 1234.6
(p=5,s=1)123.456
(p=6,s=3) => could be truncated into 123.46
(p=5,s=2)123450
(p=6,s=0) => out of rangeNote that the range is generally defined by the precision: |value| < 10^p
...
I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer
The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.
That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!
<style>
html, body {
height: 100%;
}
#tableContainer-1 {
height: 100%;
width: 100%;
display: table;
}
#tableContainer-2 {
vertical-align: middle;
display: table-cell;
height: 100%;
}
#myTable {
margin: 0 auto;
}
</style>
<div id="tableContainer-1">
<div id="tableContainer-2">
<table id="myTable" border>
<tr><td>Name</td><td>J W BUSH</td></tr>
<tr><td>Proficiency</td><td>PHP</td></tr>
<tr><td>Company</td><td>BLAH BLAH</td></tr>
</table>
</div>
</div>
I had a similar problem with a new Apache web directory (account created with WHM) that I planned to use as a staging web server. I needed to initially clone my new project with the code base there and periodically deploy changes by pulling from repository.
The problem was that the account already contained web server files like:
.bash_history
.bash_logout
.bash_profile
.bashrc
.contactemail
.cpanel/
...
...that I did not want to either delete or commit to my repository. I needed them to just stay there unstaged and untracked.
What I did:
I went to my web folder (existing_folder):
cd /home/existing_folder
and then:
git init
git remote add origin PATH/TO/REPO
git pull origin master
git status
It displayed (as expected) a list of many not staged files - those that already existed initially from my cPanel web account.
Then, thanks to this article, I just added the list of those files to:
**.git/info/exclude**
This file, almost like the .gitignore
file, allows you to ignore files from being staged. After this I had nothing to commit in the .git/ directory - it works like a personal .gitignore
that no one else can see.
Now checking git status
returns:
On branch master
nothing to commit, working tree clean
Now I can deploy changes to this web server by simply pulling from my git repository. Hope this helps some web developers to easily create a staging server.
Here is a working example in side a function:
function setCurrency(){_x000D_
var returnCurrent;_x000D_
$("#RequestCurrencyType").is(":checked") === true ? returnCurrent = 'Dollar': returnCurrent = 'Euro';_x000D_
_x000D_
return returnCurrent;_x000D_
}
_x000D_
In your case. Change the selector and the return values
$("#blackbox").css('background-color') === 'pink' ? return "black" : return "pink";
_x000D_
lastly, to know what is the value used by the browser run the following in the console:
$("#blackbox").css('background-color')
_x000D_
and use the "rgb(xxx.xxx.xxx)" value instead of the Hex for the color selection.
My reading of the docs is that HttpConnection itself is not treated as thread safe, and hence MultiThreadedHttpConnectionManager provides a reusable pool of HttpConnections, you have a single MultiThreadedHttpConnectionManager shared by all threads and initialised exactly once. So you need a couple of small refinements to option A.
MultiThreadedHttpConnectionManager connman = new MultiThreadedHttpConnectionManag
Then each thread should be using the sequence for every request, getting a conection from the pool and putting it back on completion of its work - using a finally block may be good. You should also code for the possibility that the pool has no available connections and process the timeout exception.
HttpConnection connection = null
try {
connection = connman.getConnectionWithTimeout(
HostConfiguration hostConfiguration, long timeout)
// work
} catch (/*etc*/) {/*etc*/} finally{
if ( connection != null )
connman.releaseConnection(connection);
}
As you are using a pool of connections you won't actually be closing the connections and so this should not hit the TIME_WAIT problem. This approach does assuume that each thread doesn't hang on to the connection for long. Note that conman itself is left open.
how to set center of the textboxes
I don't think that best practice will be passing a variable like req.YOUR_VAR
. You might want to consider req.YOUR_APP_NAME.YOUR_VAR
or req.mw_params.YOUR_VAR
.
It will help you avoid overwriting other attributes.
Update May 31, 2020
res.locals is what you're looking for, the object is scoped to the request.
An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
For Android Studio:
If you haven't built the APK at least once, you might not find the /Outputs/APK folder. Go to Build in Android Studio and one of the last three options is Build APK, select that. It will then create that folder and you will find your APK file there.
Quite simple, quite permissive. It will have false positives like -notvalid.at-all, but it won't have false negatives.
/^([0-9a-z-]+\.?)+$/i
It makes sure it has a sequence of letters numbers and dashes that could end with a dot, and following it, any number of those kind of sequences.
The things I like about this regexp: it's short (maybe the shortest here), easily understandable, and good enough for validating user input errors in the client side.
Or by using DBI
s sqlRownamesToColumn
library(DBI)
sqlRownamesToColumn(df)
DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;
$(function (){
$('body').on('keypress','.sobitie_snses input',function(e){
if(e.keyCode==13){
$(this).blur();
var new_fild = $(this).clone().val('');
$(this).parent().append(new_fild);
$(new_fild).focus();
}
});
});
most of error are because U use wrong object to set the prorepty or function. Use console.log(new_fild); to see to what object U try to set the prorepty or function.
implementation 'com.android.support:appcompat-v7:28.0'
implementation 'com.android.support:support-media-compat:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
All to add
Most (if not all) implementations proposed here have two flaws:
An updated proposition:
def find_first_in_list(objects, **kwargs):
return next((obj for obj in objects if
len(set(obj.keys()).intersection(kwargs.keys())) > 0 and
all([obj[k] == v for k, v in kwargs.items() if k in obj.keys()])),
None)
Maybe not the most pythonic, but at least a bit more failsafe.
Usage:
>>> obj1 = find_first_in_list(list_of_dict, name='Pam', age=7)
>>> obj2 = find_first_in_list(list_of_dict, name='Pam', age=27)
>>> obj3 = find_first_in_list(list_of_dict, name='Pam', address='nowhere')
>>>
>>> print(obj1, obj2, obj3)
{"name": "Pam", "age": 7}, None, {"name": "Pam", "age": 7}
The gist.
My suggestion to you is to select Launch Image Source as Image.Assets. Create splash image assets there in Image.assests folder.
Here are the steps:
Close the file
$select = "data what we trying to store in a file";
$file = fopen("/var/www/htdocs/folder/test.txt", "w");
fwrite($file, $select->__toString());
fclose($file);
<form>
<fieldset class="form-group"><input type="text" class="form-control" placeholder="Input"/></fieldset>
<fieldset class="form-group"><button class="btn btn-primary"/>Button</fieldset>
</form>
http://v4-alpha.getbootstrap.com/components/forms/#form-controls
"hello _there_".replace(/_(.*?)_/, function(a, b){
return '<div>' + b + '</div>';
})
Oh, or you could also:
"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")
EDIT by Liran H:
For six other people including myself, $1
did not work, whereas \1
did.
Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
@Override
public void afterTextChanged(Editable arg0) {}
});
The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.
EDIT
To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.
class CustomAdapter extends BaseAdapter implements Filterable {
public View getView(){
...
}
public Integer getCount()
{
...
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayListNames = (List<String>) results.values;
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<String> FilteredArrayNames = new ArrayList<String>();
// perform your search here using the searchConstraint String.
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mDatabaseOfNames.size(); i++) {
String dataNames = mDatabaseOfNames.get(i);
if (dataNames.toLowerCase().startsWith(constraint.toString())) {
FilteredArrayNames.add(dataNames);
}
}
results.count = FilteredArrayNames.size();
results.values = FilteredArrayNames;
Log.e("VALUES", results.values.toString());
return results;
}
};
return filter;
}
}
Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.
@coldmind answer is correct but lacks details.
The 'NOT NULL constraint failed' occurs when something tries to set None to the 'zipcode' property, while it has not been explicitely allowed.
It usually happens when:
1) your field has Null=False by default, so that the value in the database cannot be None (i.e. undefined) when the object is created and saved in the database (this happens after a objects_set.create() call or setting the .zipcode property and doing a .save() call).
For instance, if somewhere in your code an assignement results in:
model.zipcode = None
this error is raised
2) When creating or updating the database, Django is constrained to find a default value to fill the field, because Null=False by default. It does not find any because you haven't defined any. So this error can not only happen during code execution but also when creating the database?
3) Note that the same error would be returned of you define default=None, or if your default value with an incorrect type, for instance default='00000' instead of 00000 for your field (maybe can there be automatic conversion between char and integers, but I would advise against relying on it. Besides, explicit is better than implicit). Most likely an error would also be raised if the default value violates the max_length property, e.g. 123456
So you'll have to define the field by one of the following:
models.IntegerField(_('zipcode'), max_length=5, Null=True,
blank=True)
models.IntegerField(_('zipcode'), max_length=5, Null=False,
blank=True, default=00000)
models.IntegerField(_('zipcode'), max_length=5, blank=True,
default=00000)
and then make a migration (python3 manage.py makemigration ) and then migrate (python3 manage.py migrate).
For safety you can also delete the last failed migration files in <app_name>/migrations/, there are usually named after this pattern:
<NUMBER>_auto_<DATE>_<HOUR>.py
Finally, if you don't set Null=True, make sure that mode.zipcode = None is never done anywhere.
Unbind the mouseenter
and mouseleave
events individually or unbind all events on the element(s).
$(this).unbind('mouseenter').unbind('mouseleave');
or
$(this).unbind(); // assuming you have no other handlers you want to keep
The pattern matches all non-digit characters. This will restrict you to non-negative integers, but for your example it will be more than sufficient.
string input = "0, 10, 20, 30, 100, 200";
Regex.Split(input, @"\D+");
Well, In my case Mockito error was telling me to call the actual method after the when
or whenever
stub. Since we were not invoking the conditions that we just mocked, Mockito was reporting that as unnecessary stubs or code.
Here is what it was like when the error was coming :
@Test
fun `should return error when item list is empty for getStockAvailability`() {
doAnswer(
Answer<Void> { invocation ->
val callback =
invocation.arguments[1] as GetStockApiCallback<StockResultViewState.Idle, StockResultViewState.Error>
callback.onApiCallError(stockResultViewStateError)
null
}
).whenever(stockViewModelTest)
.getStockAvailability(listOf(), getStocksApiCallBack)
}
then I just called the actual method mentioned in when statement to mock the method.
changes done is as below
stockViewModelTest.getStockAvailability(listOf(), getStocksApiCallBack)
@Test
fun `should return error when item list is empty for getStockAvailability`() {
doAnswer(
Answer<Void> { invocation ->
val callback =
invocation.arguments[1] as GetStockApiCallback<StockResultViewState.Idle, StockResultViewState.Error>
callback.onApiCallError(stockResultViewStateError)
null
}
).whenever(stockViewModelTest)
.getStockAvailability(listOf(), getStocksApiCallBack)
//called the actual method here
stockViewModelTest.getStockAvailability(listOf(), getStocksApiCallBack)
}
it's working now.
Or much easier use SciPy
from scipy import ndimage
#rotation angle in degree
rotated = ndimage.rotate(image_to_rotate, 45)
see here for more usage info.
Yes and no. The solution is to build a Wrapper clas for your values that contains the 2 (3, or more) values that correspond to your key.
Visual Leak Detector (VLD) is a free, robust, open-source memory leak detection system for Visual C++.
When you run your program under the Visual Studio debugger, Visual Leak Detector will output a memory leak report at the end of your debugging session. The leak report includes the full call stack showing how any leaked memory blocks were allocated. Double-click on a line in the call stack to jump to that file and line in the editor window.
If you only have crash dumps, you can use the Windbg !heap -l
command, it will detect leaked heap blocks. Better open the gflags option: “Create user mode stack trace database”, then you will see the memory allocation call stack.
I like this solution from a similar question. https://stackoverflow.com/a/25036303/2364401 Use bootstraps text-center
class on the actual table data <td>
and table header <th>
elements. So
<td class="text-center">Cell data</td>
and
<th class="text-center">Header cell data</th>
Try =Year(Now())
and format the cell as General
.
typeof(T).Name // class name, no namespace
typeof(T).FullName // namespace and class name
typeof(T).Namespace // namespace, no class name
I'd use datediff
, and not care about format conversions:
SELECT *
FROM mytable
WHERE DATEDIFF(MONTH, my_date_column, GETDATE()) <= 3
This is pure JavaScript solution. Which I was required.
I tried on different browsers. It is working fine. Hope it helps.
How do I detect the browser name ?
You can use the navigator.appName
and navigator.userAgent
properties. The userAgent
property is more reliable than appName
because, for example, Firefox (and some other browsers) may return the string "Netscape" as the value of navigator.appName
for compatibility with Netscape Navigator.
Note, however, that navigator.userAgent
may be spoofed, too – that is, clients may substitute virtually any string for their userAgent
. Therefore, whatever we deduce from either appName
or userAgent
should be taken with a grain of salt.
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) {
browserName = nAgt.substring(nameOffset,verOffset);
fullVersion = nAgt.substring(verOffset+1);
if (browserName.toLowerCase()==browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
document.write(''
+'Browser name = '+browserName+'<br>'
+'Full version = '+fullVersion+'<br>'
+'Major version = '+majorVersion+'<br>'
+'navigator.appName = '+navigator.appName+'<br>'
+'navigator.userAgent = '+navigator.userAgent+'<br>');
Adding on to Carlos Calla's great answer.
The height of .modal-body must be set, BUT you can use media queries to make sure it's appropriate for the screen size.
.modal-body{
height: 250px;
overflow-y: auto;
}
@media (min-height: 500px) {
.modal-body { height: 400px; }
}
@media (min-height: 800px) {
.modal-body { height: 600px; }
}
If someone has the same issue as I had - make sure that you don't install from the Ubuntu 14.04 repo onto a 12.04 machine - it gives this same error. Reinstalling from the proper repository fixed the issue.
Late to the party - here as a pure java solution for those when JNI is not an option.JTransforms
in my case, this error is raised due to sequence was not created..
CREATE SEQUENCE J.SOME_SEQ MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE ;
# dump into file
pg_dump myDB > /tmp/myDB.sql
# create an empty db with the right encoding (on older versions the escaped single quotes are needed!)
psql -c 'CREATE DATABASE "tempDB" WITH OWNER = "myself" LC_COLLATE = '\''de_DE.utf8'\'' TEMPLATE template0;'
# import in the new DB
psql -d tempDB -1 -f /tmp/myDB.sql
# rename databases
psql -c 'ALTER DATABASE "myDB" RENAME TO "myDB_wrong_encoding";'
psql -c 'ALTER DATABASE "tempDB" RENAME TO "myDB";'
# see the result
psql myDB -c "SHOW LC_COLLATE"
For me: changing the listen host worked:
.listen(3000, 'localhost', function (err, result) {
if (err) {
console.log(err);
}
console.log('Listening at localhost:3000');
});
was changed to :
.listen(3000, '0.0.0.0', function (err, result) {
if (err) {
console.log(err);
}
console.log('Listening at localhost:3000');
});
and the server started listening on 0.0.0.0
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push()
method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form
, however you don't have a form on the page. In order for this to work you would need to have <form>
tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick
attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert()
function uses the references to each input field to get their value. It then uses the push()
method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow()
function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value
property of each input to an empty string. It then clears out the .innerHTML
of our message box. Lastly, it calls the join()
method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
Resized VM with more memory fixed this issue.
If you want to do it with phpmyadmin interface:
Select the table -> Go to structure tab -> On the row corresponding to the column you want, click on the icon with a key
someone here may find it useful. hhb_curl_exec2 works pretty much like curl_exec, but arg3 is an array which will be populated with the returned http headers (numeric index), and arg4 is an array which will be populated with the returned cookies ($cookies["expires"]=>"Fri, 06-May-2016 05:58:51 GMT"), and arg5 will be populated with... info about the raw request made by curl.
the downside is that it requires CURLOPT_RETURNTRANSFER to be on, else it error out, and that it will overwrite CURLOPT_STDERR and CURLOPT_VERBOSE, if you were already using them for something else.. (i might fix this later)
example of how to use it:
<?php
header("content-type: text/plain;charset=utf8");
$ch=curl_init();
$headers=array();
$cookies=array();
$debuginfo="";
$body="";
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$body=hhb_curl_exec2($ch,'https://www.youtube.com/',$headers,$cookies,$debuginfo);
var_dump('$cookies:',$cookies,'$headers:',$headers,'$debuginfo:',$debuginfo,'$body:',$body);
and the function itself..
function hhb_curl_exec2($ch, $url, &$returnHeaders = array(), &$returnCookies = array(), &$verboseDebugInfo = "")
{
$returnHeaders = array();
$returnCookies = array();
$verboseDebugInfo = "";
if (!is_resource($ch) || get_resource_type($ch) !== 'curl') {
throw new InvalidArgumentException('$ch must be a curl handle!');
}
if (!is_string($url)) {
throw new InvalidArgumentException('$url must be a string!');
}
$verbosefileh = tmpfile();
$verbosefile = stream_get_meta_data($verbosefileh);
$verbosefile = $verbosefile['uri'];
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, $verbosefileh);
curl_setopt($ch, CURLOPT_HEADER, 1);
$html = hhb_curl_exec($ch, $url);
$verboseDebugInfo = file_get_contents($verbosefile);
curl_setopt($ch, CURLOPT_STDERR, NULL);
fclose($verbosefileh);
unset($verbosefile, $verbosefileh);
$headers = array();
$crlf = "\x0d\x0a";
$thepos = strpos($html, $crlf . $crlf, 0);
$headersString = substr($html, 0, $thepos);
$headerArr = explode($crlf, $headersString);
$returnHeaders = $headerArr;
unset($headersString, $headerArr);
$htmlBody = substr($html, $thepos + 4); //should work on utf8/ascii headers... utf32? not so sure..
unset($html);
//I REALLY HOPE THERE EXIST A BETTER WAY TO GET COOKIES.. good grief this looks ugly..
//at least it's tested and seems to work perfectly...
$grabCookieName = function($str)
{
$ret = "";
$i = 0;
for ($i = 0; $i < strlen($str); ++$i) {
if ($str[$i] === ' ') {
continue;
}
if ($str[$i] === '=') {
break;
}
$ret .= $str[$i];
}
return urldecode($ret);
};
foreach ($returnHeaders as $header) {
//Set-Cookie: crlfcoookielol=crlf+is%0D%0A+and+newline+is+%0D%0A+and+semicolon+is%3B+and+not+sure+what+else
/*Set-Cookie:ci_spill=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22305d3d67b8016ca9661c3b032d4319df%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%2285.164.158.128%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A109%3A%22Mozilla%2F5.0+%28Windows+NT+6.1%3B+WOW64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F43.0.2357.132+Safari%2F537.36%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1436874639%3B%7Dcab1dd09f4eca466660e8a767856d013; expires=Tue, 14-Jul-2015 13:50:39 GMT; path=/
Set-Cookie: sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT;
//Cookie names cannot contain any of the following '=,; \t\r\n\013\014'
//
*/
if (stripos($header, "Set-Cookie:") !== 0) {
continue;
/**/
}
$header = trim(substr($header, strlen("Set-Cookie:")));
while (strlen($header) > 0) {
$cookiename = $grabCookieName($header);
$returnCookies[$cookiename] = '';
$header = substr($header, strlen($cookiename) + 1); //also remove the =
if (strlen($header) < 1) {
break;
}
;
$thepos = strpos($header, ';');
if ($thepos === false) { //last cookie in this Set-Cookie.
$returnCookies[$cookiename] = urldecode($header);
break;
}
$returnCookies[$cookiename] = urldecode(substr($header, 0, $thepos));
$header = trim(substr($header, $thepos + 1)); //also remove the ;
}
}
unset($header, $cookiename, $thepos);
return $htmlBody;
}
function hhb_curl_exec($ch, $url)
{
static $hhb_curl_domainCache = "";
//$hhb_curl_domainCache=&$this->hhb_curl_domainCache;
//$ch=&$this->curlh;
if (!is_resource($ch) || get_resource_type($ch) !== 'curl') {
throw new InvalidArgumentException('$ch must be a curl handle!');
}
if (!is_string($url)) {
throw new InvalidArgumentException('$url must be a string!');
}
$tmpvar = "";
if (parse_url($url, PHP_URL_HOST) === null) {
if (substr($url, 0, 1) !== '/') {
$url = $hhb_curl_domainCache . '/' . $url;
} else {
$url = $hhb_curl_domainCache . $url;
}
}
;
curl_setopt($ch, CURLOPT_URL, $url);
$html = curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception('Curl error (curl_errno=' . curl_errno($ch) . ') on url ' . var_export($url, true) . ': ' . curl_error($ch));
// echo 'Curl error: ' . curl_error($ch);
}
if ($html === '' && 203 != ($tmpvar = curl_getinfo($ch, CURLINFO_HTTP_CODE)) /*203 is "success, but no output"..*/ ) {
throw new Exception('Curl returned nothing for ' . var_export($url, true) . ' but HTTP_RESPONSE_CODE was ' . var_export($tmpvar, true));
}
;
//remember that curl (usually) auto-follows the "Location: " http redirects..
$hhb_curl_domainCache = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL), PHP_URL_HOST);
return $html;
}
In my case, I made the change on my hard drive (cut/pasted about 200 folders/files from one path in my working copy to another path in my working copy), and used SourceTree (2.0.20.1) to stage both the detected changes (one add, one remove), and as long as I staged both the add and remove together, it automatically combined into a single change with a pink R icon (rename I assume).
I did notice that because I had such a large number of changes at once, SourceTree was a little slow detecting all the changes, so some of my staged files look like just adds (green plus) or just deletes (red minus), but I kept refreshing the file status and kept staging new changes as they eventually popped up, and after a few minutes, the whole list was perfect and ready for commit.
I verified that the history is present, as long as when I look for history, I check the "Follow renamed files" option.
private void Log(string s , Color? c = null)
{
richTextBox.SelectionStart = richTextBox.TextLength;
richTextBox.SelectionLength = 0;
richTextBox.SelectionColor = c ?? Color.Black;
richTextBox.AppendText((richTextBox.Lines.Count() == 0 ? "" : Environment.NewLine) + DateTime.Now + "\t" + s);
richTextBox.SelectionColor = Color.Black;
}
The new django.urls.path()
function allows a simpler, more readable URL routing syntax. For example, this example from previous Django releases:
url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive)
could be written as:
path('articles/<int:year>/', views.year_archive)
The django.conf.urls.url()
function from previous versions is now available as django.urls.re_path()
. The old location remains for backwards compatibility, without an imminent deprecation. The old django.conf.urls.include()
function is now importable from django.urls
so you can use:
from django.urls import include, path, re_path
in the URLconfs. For further reading django doc
run xampp shell to solve connect to root using pw
mysql -h localhost -u root -p
and enter root pw
I stumbled on this question trying to get the organization/repo
string from a git host like github or gitlab.
This is working for me:
git config --get remote.origin.url | sed -e 's/^git@.*:\([[:graph:]]*\).git/\1/'
It uses sed
to replace the output of the git config
command with just the organization and repo name.
Something like github/scientist
would be matched by the character class [[:graph:]]
in the regular expression.
The \1
tells sed to replace everything with just the matched characters.
(For Ubuntu users)
I had the same problem, but none of the answers above solved that. Here is how I solved the problem.
Open your php.ini
file (mine was in /etc/php/7.3/cli/php.ini
).
You may have something like this:
extension=pdo_mysql
Or maybe:
extension=/here/is/the/path/to/your/file/pdo_mysql.so
Add the following line before extension=pdo_mysql
extension=pdo
So, you will have:
extension=pdo
extension=pdo_mysql
It seems that the problem is (at least in my case) that we need to load pdo
extension first to load the pdo_mysql
extension.
Hope that helps!
Solved! The call build job: project, parameters: params
fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List
when params = [:]
. Replacing it with params = null
solved the issue.
Here the working code below.
def doCopyMibArtefactsHere(projectName) {
step ([
$class: 'CopyArtifact',
projectName: projectName,
filter: '**/**.mib',
fingerprintArtifacts: true,
flatten: true
]);
}
def BuildAndCopyMibsHere(projectName, params = null) {
build job: project, parameters: params
doCopyMibArtefactsHere(projectName)
}
node {
stage('Prepare Mib'){
BuildAndCopyMibsHere('project1')
}
}
This will help
wget -m -np -c --level 0 --no-check-certificate -R"index.html*"http://www.your-websitepage.com/dir
I have another solution that works great.
On one hand, Ortwin's approach & solution works only with iOS 6.0 and later, but fails to work correctly on iOS 5.0, 5.1 and 5.1.1, and on the other hand there is something that I don't like and can't understand with Ortwin's approach, it's the use of the method [webView sizeThatFits:CGSizeZero]
with the parameter CGSizeZero
: If you read Apple Official documentation about this methods and its parameter, it says clearly :
The default implementation of this method returns the size portion of the view’s bounds rectangle. Subclasses can override this method to return a custom value based on the desired layout of any subviews. For example, a UISwitch object returns a fixed size value that represents the standard size of a switch view, and a UIImageView object returns the size of the image it is currently displaying.
What I mean is that it's like he came across his solution without any logic, because reading the documentation, the parameter passed to [webView sizeThatFits: ...]
should at least have the desired width
. With his solution, the desired width is set to the webView
's frame before calling sizeThatFits
with a CGSizeZero
parameter. So I maintain this solution is working on iOS 6 by "chance".
I imagined a more rational approach, which has the advantage of working for iOS 5.0 and later... And also in complex situations where more than one webView (With its property webView.scrollView.scrollEnabled = NO
is embedded in a scrollView
.
Here is my code to force the Layout of the webView
to the desired width
and get the corresponding height
set back to the webView
itself:
Obj-C
- (void)webViewDidFinishLoad:(UIWebView *)aWebView
{
aWebView.scrollView.scrollEnabled = NO; // Property available in iOS 5.0 and later
CGRect frame = aWebView.frame;
frame.size.width = 200; // Your desired width here.
frame.size.height = 1; // Set the height to a small one.
aWebView.frame = frame; // Set webView's Frame, forcing the Layout of its embedded scrollView with current Frame's constraints (Width set above).
frame.size.height = aWebView.scrollView.contentSize.height; // Get the corresponding height from the webView's embedded scrollView.
aWebView.frame = frame; // Set the scrollView contentHeight back to the frame itself.
}
Swift 4.x
func webViewDidFinishLoad(_ aWebView: UIWebView) {
aWebView.scrollView.isScrollEnabled = false
var frame = aWebView.frame
frame.size.width = 200
frame.size.height = 1
aWebView.frame = frame
frame.size.height = aWebView.scrollView.contentSize.height
aWebView.frame = frame;
}
Note that in my example, the webView
was embedded in a custom scrollView
having other webViews
... All these webViews
had their webView.scrollView.scrollEnabled = NO
, and the last piece of code I had to add was the calculation of the height
of the contentSize
of my custom scrollView
embedding these webViews
, but it was as easy as summing my webView
's frame.size.height
computed with the trick described above...
I know this is a long cold question, but it comes up every time there is a new or recent major Java release. Now this would easily apply to 6 and 7 swapping.
I have done this in the past with update-java-alternatives
:
http://manpages.ubuntu.com/manpages/hardy/man8/update-java-alternatives.8.html
Here is a neat and simple one. Can check git remote -v
, which shows you all the origin and upstream of current branch.
I had similar issue on MacBook Pro, I just followed the below link and issue got resolved. https://projectlombok.org/setup/eclipse
Steps followed:-
If every input asks the same question, you should use a for
loop and an array of inputs:
Scanner dd = new Scanner(System.in);
int[] vars = new int[3];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}
Or as Chip suggested, you can parse the input from one line:
Scanner in = new Scanner(System.in);
int[] vars = new int[3];
System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
vars[i] = in.nextInt();
You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.
You can get textbox value and Id by the following simple example in dotNet programming
<html>
<head>
<script type="text/javascript">
function GetTextboxId_Value(textBox)
{
alert(textBox.value); // To get Text Box Value(Text)
alert(textBox.id); // To get Text Box Id like txtSearch
}
</script>
</head>
<body>
<input id="txtSearch" type="text" onkeyup="GetTextboxId_Value(this)" /> </body>
</html>
I've made a category from @Abizern answer
@implementation NSString (Extensions)
- (NSDictionary *) json_StringToDictionary {
NSError *error;
NSData *objectData = [self dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&error];
return (!json ? nil : json);
}
@end
Use it like this,
NSString *jsonString = @"{\"2\":\"3\"}";
NSLog(@"%@",[jsonString json_StringToDictionary]);
None of the existing answers to this old question address the real problem.
The real problem was that xs:complexType
cannot directly have a xs:extension
as a child in XSD. The fix is to use xs:simpleContent
first. Details follow...
Your XML,
<price currency="euros">20000.00</price>
will be valid against either of the following corrected XSDs:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="price">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:decimal">
<xs:attribute name="currency">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="pounds" />
<xs:enumeration value="euros" />
<xs:enumeration value="dollars" />
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:schema>
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:simpleType name="currencyType">
<xs:restriction base="xs:string">
<xs:enumeration value="pounds" />
<xs:enumeration value="euros" />
<xs:enumeration value="dollars" />
</xs:restriction>
</xs:simpleType>
<xs:element name="price">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:decimal">
<xs:attribute name="currency" type="currencyType"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:schema>
price
from xs:string
to xs:decimal
, but this is not strictly
necessary and was not the real problem.xs:decimal
, but
this too was not the real problem.The real problem was that xs:complexType
cannot directly have a xs:extension
as a child in XSD; xs:simpleContent
is needed first.
A related matter (that wasn't asked but may have confused other answers):
How could price
be restricted given that it has an attribute?
In this case, a separate, global definition of priceType
would be needed; it is not possible to do this with only local type definitions.
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:simpleType name="priceType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0.00"/>
<xs:maxInclusive value="99999.99"/>
</xs:restriction>
</xs:simpleType>
<xs:element name="price">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="priceType">
<xs:attribute name="currency">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="pounds" />
<xs:enumeration value="euros" />
<xs:enumeration value="dollars" />
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:schema>
Issue happens because Microsoft Security Update MS11-100 limits number of keys in Forms collection during HTTP POST request. To alleviate this problem you need to increase that number.
This can be done in your application Web.Config in the
<appSettings>
section (create the section directly under<configuration>
if it doesn’t exist). Add 2 lines similar to the lines below to the section:<add key="aspnet:MaxHttpCollectionKeys" value="2000" /> <add key="aspnet:MaxJsonDeserializerMembers" value="2000" />
The above example set the limit to 2000 keys. This will lift the limitation and the error should go away.
[1,2,3].uniq!.nil? => true
[1,2,3,3].uniq!.nil? => false
Notice the above is destructive
One thing that caught me out and surprised me was, in an inherited project, the files it was referring to were referred to on a relative path outside of the project folder but yet existed in the project folder.
In solution explorer, single click each file with the error, bring up the Properties window (right-click, Properties), and ensure the "Relative Path" is just the file name (e.g. MyMissingFile.cpp
) if it is in the project folder. In my case it was set to: ..\..\Some Other Folder\MyMissingFile.cpp
.
The universal tool for string formatting, sprintf
:
$stamp = sprintf('%s%02s', $year, $month);
To target IE10 and IE11 only (and not Edge):
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
/* add your IE10-IE11 css here */
}
Scanner's buffer full when we take a input string through scan.nextLine(); so it skips the input next time . So solution is that we can create a new object of Scanner , the name of the object can be same as previous object......