Structure is a data type. You don't give values to a data type. You give values to instances/objects of data types.
So no this is not possible in C.
Instead you can write a function which does the initialization for structure instance.
Alternatively, You could do:
struct MyStruct_s
{
int id;
} MyStruct_default = {3};
typedef struct MyStruct_s MyStruct;
And then always initialize your new instances as:
MyStruct mInstance = MyStruct_default;
As some other answers have already pointed out, there are many reasons why celery would silently ignore tasks, including dependency issues but also any syntax or code problem.
One quick way to find them is to run:
./manage.py check
Many times, after fixing the errors that are reported, the tasks are recognized by celery.
And here's a jQuery example:
HTML text field:
<input type="text" id="myTextfield" />
jQuery code to limit its size:
var elem = $("#myTextfield");
if(elem) elem.val(elem.val().substr(0,10));
As an example, you could use the jQuery code above to restrict the user from entering more than 10 characters while he's typing; the following code snippet does exactly this:
$(document).ready(function() {
var elem = $("#myTextfield");
if (elem) {
elem.keydown(function() {
if (elem.val().length > 10)
elem.val(elem.val().substr(0, 10));
});
}
});
Update: The above code snippet was only used to show an example usage.
The following code snippet will handle you issue with the DIV element:
$(document).ready(function() {
var elem = $(".tasks-overflow");
if(elem){
if (elem.text().length > 10)
elem.text(elem.text().substr(0,10))
}
});
Please note that I'm using text
instead of val
in this case, since the val
method doesn't seem to work with the DIV element.
With dplyr you would do:
library(dplyr)
df = data.frame(q = 1, w = 2, e = 3)
df %>% rename(A = q, B = e)
# A w B
#1 1 2 3
Or if you want to use vectors, as suggested by @Jelena-bioinf:
library(dplyr)
df = data.frame(q = 1, w = 2, e = 3)
oldnames = c("q","e")
newnames = c("A","B")
df %>% rename_at(vars(oldnames), ~ newnames)
# A w B
#1 1 2 3
L. D. Nicolas May suggested a change given rename_at
is being superseded by rename_with
:
df %>%
rename_with(~ newnames[which(oldnames == .x)], .cols = oldnames)
# A w B
#1 1 2 3
Try this:
$("#message span").text("hello world!");
See it in your code!
function Errormessage(txt) {
var m = $("#message");
// set text before displaying message
m.children("span").text(txt);
// bind close listener
m.children("a.close-notify").click(function(){
m.fadeOut("slow");
});
// display message
m.fadeIn("slow");
}
I encountered a point (not explictly yet mentioned?) which I was stumbling over. That is, not how to return the boolean, but rather how to correctly evaluate it!
I was trying to say if [ myfunc ]; then ...
, but that's simply wrong. You must not use the brackets! if myfunc; then ...
is the way to do it.
As at @Bruno and others reiterated, true
and false
are commands, not values! That's very important to understanding booleans in shell scripts.
In this post, I explained and demoed using boolean variables: https://stackoverflow.com/a/55174008/3220983 . I strongly suggest checking that out, because it's so closely related.
Here, I'll provide some examples of returning and evaluating booleans from functions:
This:
test(){ false; }
if test; then echo "it is"; fi
Produces no echo output. (i.e. false
returns false)
test(){ true; }
if test; then echo "it is"; fi
Produces:
it is
(i.e. true
returns true)
And
test(){ x=1; }
if test; then echo "it is"; fi
Produces:
it is
Because 0 (i.e. true) was returned implicitly.
Now, this is what was screwing me up...
test(){ true; }
if [ test ]; then echo "it is"; fi
Produces:
it is
AND
test(){ false; }
if [ test ]; then echo "it is"; fi
ALSO produces:
it is
Using the brackets here produced a false positive! (I infer the "outer" command result is 0.)
The major take away from my post is: don't use brackets to evaluate a boolean function (or variable) like you would for a typical equality check e.g. if [ x -eq 1 ]; then...
!
Basically: assign a keyup
handler to the <textarea>
element, in it count the length of the <textarea>
and write the count to a separate <div>
if its length is shorter than a minimum value.
Here's is an example-
var min = 15;_x000D_
document.querySelector('#tst').onkeyup = function(e){_x000D_
document.querySelector('#counter').innerHTML = _x000D_
this.value.length < min _x000D_
? (min - this.value.length)+' to go...'_x000D_
: '';_x000D_
}_x000D_
_x000D_
body {font: normal 0.8em verdana, arial;}_x000D_
#counter {color: grey}
_x000D_
<textarea id="tst" cols="60" rows="10"></textarea>_x000D_
<div id="counter"></div>
_x000D_
It's simply a matter of scaling the image width and height up by the correct ratio. Not all images formats support a DPI metatag, and when they do, all they're telling your graphics software to do is divide the image by the ratio supplied.
For example, if you export a 300dpi image from Photoshop to a JPEG, the image will appear to be very large when viewed in your picture viewing software. This is because the DPI information isn't supported in JPEG and is discarded when saved. This means your picture viewer doesn't know what ratio to divide the image by and instead displays the image at at 1:1 ratio.
To get the ratio you need to scale the image by, see the code below. Just remember, this will stretch the image, just like it would in Photoshop. You're essentially quadrupling the size of the image so it's going to stretch and may produce artifacts.
Pseudo code
ratio = 300.0 / 72.0 // 4.167
image.width * ratio
image.height * ratio
jsonObj.profile-id
is a subtraction expression (i.e. jsonObj.profile - id
).
To access a key that contains characters that cannot appear in an identifier, use brackets:
jsonObj["profile-id"]
I know there are lots of solutions to this already, but I thought I'll just mention what solved it for me.
My configuration was set to Debug. Changing it to Release did the trick for me.
I found this solution via PowerShell :
dir | rename-item -NewName {$_.name -replace "replaceME","MyNewTxt"}
This will rename parts of all the files in the current folder.
Use <f:convertDateTime>
. You can nest this in any input and output component. Pattern rules are same as java.text.SimpleDateFormat
.
<h:outputText value="#{someBean.dateField}" >
<f:convertDateTime pattern="dd.MM.yyyy HH:mm" />
</h:outputText>
Something like:
var rnd = new Random(DateTime.Now.Millisecond);
int ticks = rnd.Next(0, 3000);
An alternative to the proposed:
QString qs;
std::string current_locale_text = qs.toLocal8Bit().constData();
could be:
QString qs;
std::string current_locale_text = qPrintable(qs);
See qPrintable documentation, a macro delivering a const char * from QtGlobal.
Try to set ENV PATH. Add PHP path in to ENV PATH.
In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libeay32.dll
@Html.TextBoxFor(model => model.IdUsuario, new { @Value = "" + User.Identity.GetUserId() + "", @disabled = "true" })
@disabled = "true"
Work very well
I just need to initialize all the array elements to Boolean false.
Either use boolean[]
instead so that all values defaults to false
:
boolean[] array = new boolean[size];
Or use Arrays#fill()
to fill the entire array with Boolean.FALSE
:
Boolean[] array = new Boolean[size];
Arrays.fill(array, Boolean.FALSE);
Also note that the array index is zero based. The freq[Global.iParameter[2]] = false;
line as you've there would cause ArrayIndexOutOfBoundsException
. To learn more about arrays in Java, consult this basic Oracle tutorial.
In C# 6 you can use string interpolation:
string name = "John";
string result = $"Hello {name}";
The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.
if you want to add row at the end append it as a list
valuestoappend = [va1,val2,val3]
res = res.append(pd.Series(valuestoappend,index = ['lib', 'qty1', 'qty2']),ignore_index = True)
Shortcut for static import: CTRL + SHIFT + M
Add this to your .htaccess code
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]
Replace www.yourdomain.com with your domain name. This will force all the urls of your domain to use https. Make sure you have https certificate installed and configured on your domain. If you do not see https in green as secure, press f12 on chrome and fix all the mixed errors in the console tab.
Hope this helps!
If you don't wish to use 3rd party classes then the following is how you set the post body...
NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
delegate:self];
Simply append your key/value pair to the post string
var1
is a regular string, whereas var2
is an array, this is how you should compare (in this case):
puts var1 == var2[0]
1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.
2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):
This rule will do SINGLE EXACT rewrite (internal redirect) /page
to /page.html
. URL in browser will remain unchanged.
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRewrite" stopProcessing="true">
<match url="^page$" />
<action type="Rewrite" url="/page.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRedirect" stopProcessing="true">
<match url="^page$" />
<action type="Redirect" url="/page.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page
it will check if /page.html
exists, and if it does then rewrite occurs):
<system.webServer>
<rewrite>
<rules>
<rule name="DynamicRewrite" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
</conditions>
<action type="Rewrite" url="/{R:1}.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
In addition to previously provided answers, one option is to follow the 'localhost exception' approach to create the first user if your db is already started with access control (--auth
switch). In order to do that, you need to have localhost access to the server and then run:
mongo
use admin
db.createUser(
{
user: "user_name",
pwd: "user_pass",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" }
]
})
As stated in MongoDB documentation:
The localhost exception allows you to enable access control and then create the first user in the system. With the localhost exception, after you enable access control, connect to the localhost interface and create the first user in the admin database. The first user must have privileges to create other users, such as a user with the userAdmin or userAdminAnyDatabase role. Connections using the localhost exception only have access to create the first user on the admin database.
Here is the link to that section of the docs.
If you are not having a stroke you can use
colorDrawable = resources.getDrawable(R.drawable.x_sd_circle);
colorDrawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
but this will also change stroke color
You could add another empty layout below that one and set them both to have the same layout weight. They should get 50% of the space each.
MIME stands for Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format.
For example, using the Content-type
header value defined in a HTTP response, the browser can open the file with the proper extension/plugin.
Internet Media Type (also Content-type) is the same as a MIME type. MIME types were originally created for emails sent using the SMTP protocol. Nowadays, this standard is used in a lot of other protocols, hence the new naming convention "Internet Media Type".
A MIME type is a string identifier composed of two parts: a type
and a subtype
.
The x-
prefix of a MIME subtype simply means that it's non-standard.
The vnd
prefix means that the MIME value is vendor specific.
Why are there extra spaces between my month and day? Why does't it just put them next to each other?
So your output will be aligned.
If you don't want padding use the format modifier FM
:
SELECT TO_CHAR (date_field, 'fmMonth DD, YYYY')
FROM ...;
Reference: Format Model Modifiers
By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers:
old 1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new 1: insert into customers (customer_name) values ('Marks Ltd')
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks Ltd
If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off
to switch off the behaviour while running the script:
SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd
You might want to add set define on
at the end of the script to restore the default behaviour.
The big difference is that the first example actually invokes the lambda f(x)
, while the second example doesn't.
Your first example is equivalent to [(lambda x: x*x)(x) for x in range(10)]
while your second example is equivalent to [f for x in range(10)]
.
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
Just before I go into detail about how you can access the state of a child component, please make sure to read Markus-ipse's answer regarding a better solution to handle this particular scenario.
If you do indeed wish to access the state of a component's children, you can assign a property called ref
to each child. There are now two ways to implement references: Using React.createRef()
and callback refs.
React.createRef()
This is currently the recommended way to use references as of React 16.3 (See the docs for more info). If you're using an earlier version then see below regarding callback references.
You'll need to create a new reference in the constructor of your parent component and then assign it to a child via the ref
attribute.
class FormEditor extends React.Component {
constructor(props) {
super(props);
this.FieldEditor1 = React.createRef();
}
render() {
return <FieldEditor ref={this.FieldEditor1} />;
}
}
In order to access this kind of ref, you'll need to use:
const currentFieldEditor1 = this.FieldEditor1.current;
This will return an instance of the mounted component so you can then use currentFieldEditor1.state
to access the state.
Just a quick note to say that if you use these references on a DOM node instead of a component (e.g. <div ref={this.divRef} />
) then this.divRef.current
will return the underlying DOM element instead of a component instance.
This property takes a callback function that is passed a reference to the attached component. This callback is executed immediately after the component is mounted or unmounted.
For example:
<FieldEditor
ref={(fieldEditor1) => {this.fieldEditor1 = fieldEditor1;}
{...props}
/>
In these examples the reference is stored on the parent component. To call this component in your code, you can use:
this.fieldEditor1
and then use this.fieldEditor1.state
to get the state.
One thing to note, make sure your child component has rendered before you try to access it ^_^
As above, if you use these references on a DOM node instead of a component (e.g. <div ref={(divRef) => {this.myDiv = divRef;}} />
) then this.divRef
will return the underlying DOM element instead of a component instance.
If you want to read more about React's ref property, check out this page from Facebook.
Make sure you read the "Don't Overuse Refs" section that says that you shouldn't use the child's state
to "make things happen".
Hope this helps ^_^
Edit: Added React.createRef()
method for creating refs. Removed ES5 code.
Here's another:
data[data$Code == "A" | data$Code == "B", ]
It's also worth mentioning that the subsetting factor doesn't have to be part of the data frame if it matches the data frame rows in length and order. In this case we made our data frame from this factor anyway. So,
data[Code == "A" | Code == "B", ]
also works, which is one of the really useful things about R.
I use double quotes because I have been doing so for years in most languages (C++, Java, VB…) except Bash, because I also use double quotes in normal text and because I'm using a (modified) non-English keyboard where both characters require the shift key.
For Converting a List into Pandas Core Data Frame, we need to use DataFrame Method from pandas Package.
There are Different Ways to Perform the Above Operation.
import pandas as pd
Data = pd.DataFrame(Column_Data)
Data.columns = ['Column_Name']
So, for the above mentioned issue, the code snippet is
import pandas as pd
Content = ['Thanks You',
'Its fine no problem',
'Are you sure']
Data = pd.DataFrame({'Text': Content})
Yes you can. Since you are using spring, check out @PropertySource
anotation.
Anotate your configuration with
@PropertySource("application-${spring.profiles.active}.properties")
You can call it what ever you like, and add inn multiple property files if you like too. Can be nice if you have more sets and/or defaults that belongs to all environments (can be written with @PropertySource{...,...,...} as well).
@PropertySources({
@PropertySource("application-${spring.profiles.active}.properties"),
@PropertySource("my-special-${spring.profiles.active}.properties"),
@PropertySource("overridden.properties")})
Then you can start the application with environment
-Dspring.active.profiles=test
In this example, name will be replaced with application-test-properties and so on.
If at all you are displaying data from state variables, use this.
<Text>{this.state.user.bio.replace('<br/>', '\n')}</Text>
>>> [1,2,3,4,5,6,7,8,9][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
Late answer, but I found out that this is the simplest solution (if you don't use jQuery):
var myClasses = document.querySelectorAll('.my-class'),
i = 0,
l = myClasses.length;
for (i; i < l; i++) {
myClasses[i].style.display = 'none';
}
Have a look at this code:
HTML:
<div class="multiple-elements" data-bgcol="red"></div>
<div class="multiple-elements" data-bgcol="blue"></div>
JS:
$('.multiple-elements').each(
function(index, element) {
$(this).css('background-color', $(this).data('bgcol')); // Get value of HTML attribute data-bgcol="" and set it as CSS color
}
);
this
refers to the current element that the DOM engine is sort of working on, or referring to.
Another example:
<a href="#" onclick="$(this).css('display', 'none')">Hide me!</a>
Hope you understand now. The this
keyword occurs while dealing with object oriented systems, or as we have in this case, element oriented systems :)
This works for me:
String generateUniqueFileName() {
String filename = "";
long millis = System.currentTimeMillis();
String datetime = new Date().toGMTString();
datetime = datetime.replace(" ", "");
datetime = datetime.replace(":", "");
String rndchars = RandomStringUtils.randomAlphanumeric(16);
filename = rndchars + "_" + datetime + "_" + millis;
return filename;
}
// USE:
String newFile;
do{
newFile=generateUniqueFileName() + "." + FileExt;
}
while(new File(basePath+newFile).exists());
Output filenames should look like :
2OoBwH8OwYGKW2QE_4Sep2013061732GMT_1378275452253.Ext
Something worth taking a look at is Imran Nazar's attempt at writing a Gameboy emulator in JavaScript.
Set the aaSorting
option to an empty array. It will disable initial sorting, whilst still allowing manual sorting when you click on a column.
"aaSorting": []
The aaSorting array should contain an array for each column to be sorted initially containing the column's index and a direction string ('asc' or 'desc').
The Official Documentation is clear about Path
.
Linux Syntax: /home/joe/foo
Windows Syntax: C:\home\joe\foo
Note: joe
is your username for these examples.
Unfortunately, there's no way to do that with CSS.
It's not very difficult with JavaScript though:
// JavaScript code:
document.getElementsByClassName("active")[0].parentNode;
// jQuery code:
$('.active').parent().get(0); // This would be the <a>'s parent <li>.
I had the same error and replaced the dot notation with bracket notation to suppress it.
e.g.: obj.name -> obj['name']
Is this what you are looking for.
$("input.address_field").on('click', function(){
$(this).css('border', '2px solid red');
});
my py version is 3.7.3, and this cmd worked
python3.7 -m pip install requests
requests library - for retrieving data from web APIs.
This runs the pip module and asks it to find the requests library on PyPI.org (the Python Package Index) and install it in your local system so that it becomes available for you to import
YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".
save and open in excel, try refresh data and excel will be monit about parameters.
x.each_with_index { |v, i| puts "current index...#{i}" }
input
fields can be styled as you wish. So instead of zoom, you could have
input[type="checkbox"]{
width: 30px; /*Desired width*/
height: 30px; /*Desired height*/
}
EDIT:
You would have to add extra rules like this:
input[type="checkbox"]{
width: 30px; /*Desired width*/
height: 30px; /*Desired height*/
cursor: pointer;
-webkit-appearance: none;
appearance: none;
}
Check this fiddle http://jsfiddle.net/p36tqqyq/1/
More or less this page has answers but all are not at one place. I was dealing with the same issue and spent quite a good time on it. Now i have a better understanding and i would like to share it here:
I Enabling Swagger ui with Spring websecurity:
If you have enabled Spring Websecurity by default it will block all the requests to your application and returns 401. However for the swagger ui to load in the browser swagger-ui.html makes several calls to collect data. The best way to debug is open swagger-ui.html in a browser(like google chrome) and use developer options('F12' key ). You can see several calls made when the page loads and if the swagger-ui is not loading completely probably some of them are failing.
you may need to tell Spring websecurity to ignore authentication for several swagger path patterns. I am using swagger-ui 2.9.2 and in my case below are the patterns that i had to ignore:
However if you are using a different version your's might change. you may have to figure out yours with developer option in your browser as i said before.
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui",
"/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
, "/webjars/**", "/csrf", "/");
}
}
II Enabling swagger ui with interceptor
Generally you may not want to intercept requests that are made by swagger-ui.html. To exclude several patterns of swagger below is the code:
Most of the cases pattern for web security and interceptor will be same.
@Configuration
@EnableWebMvc
public class RetrieveCiamInterceptorConfiguration implements WebMvcConfigurer {
@Autowired
RetrieveInterceptor validationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(validationInterceptor).addPathPatterns("/**")
.excludePathPatterns("/v2/api-docs", "/configuration/ui",
"/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
, "/webjars/**", "/csrf", "/");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Since you may have to enable @EnableWebMvc to add interceptors you may also have to add resource handlers to swagger similar to i have done in the above code snippet.
The zoo
package has the function of as.yearmon
can help to convert.
require(zoo)
df$ym<-as.yearmon(df$date, "%Y %m")
as a single line:
long value_ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()).time_since_epoch()).count();
On Windows/Linux press Alt+F3.
This worked for me on Ubuntu. I changed it in my "Key-Bindings:User" to something that I liked better though.
You can created AVD, select API Level equal your tagetApi andr compileApi, it works for me.
Here is a alternative solution that should survive if the client pc goes into sleep mode.
If you have a huge amount of logged in users then use this cautiously as this could eat a lot of server memory.
After you login (i do this in the LoggedIn event of the login control)
Dim loggedOutAfterInactivity As Integer = 999 'Minutes
'Keep the session alive as long as the authentication cookie.
Session.Timeout = loggedOutAfterInactivity
'Get the authenticationTicket, decrypt and change timeout and create a new one.
Dim formsAuthenticationTicketCookie As HttpCookie = _
Response.Cookies(FormsAuthentication.FormsCookieName)
Dim ticket As FormsAuthenticationTicket = _
FormsAuthentication.Decrypt(formsAuthenticationTicketCookie.Value)
Dim newTicket As New FormsAuthenticationTicket(
ticket.Version, ticket.Name, ticket.IssueDate,
ticket.IssueDate.AddMinutes(loggedOutAfterInactivity),
ticket.IsPersistent, ticket.UserData)
formsAuthenticationTicketCookie.Value = FormsAuthentication.Encrypt(newTicket)
You can check your eav_attributes table to find the relevant attribute IDs for each image role, such as;
Then you can use those to set whichever role to any other role for all products like so;
UPDATE catalog_product_entity_varchar AS `v` INNER JOIN (SELECT `value`,`entity_id` FROM `catalog_product_entity_varchar` WHERE `attribute_id`=86) AS `j` ON `j`.`entity_id`=`v`.entity_id SET `v`.`value`=j.`value` WHERE `v`.attribute_id = 85 AND `v`.`entity_id`=`j`.`entity_id`
The above will set all your 'base' roles to the 'small' image of the same product.
(Just leaving this here for my own reference.) This will show version and build for the "version" and "build" fields you see in an Xcode target:
- (NSString*) version {
NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
return [NSString stringWithFormat:@"%@ build %@", version, build];
}
In Swift
func version() -> String {
let dictionary = NSBundle.mainBundle().infoDictionary!
let version = dictionary["CFBundleShortVersionString"] as? String
let build = dictionary["CFBundleVersion"] as? String
return "\(version) build \(build)"
}
I had the same situation and I found a way around with a bit of engineering as follows - -
You have to have your method in parent class without any parameter and use - -
Class<? extends Person> cl = this.getClass(); // inside parent class
Now, with 'cl' you can access all child class fields with their name and initialized values by using - -
cl.getDeclaredFields(); cl.getField("myfield"); // and many more
In this situation your 'this' pointer will reference your child class object if you are calling parent method through your child class object.
Another thing you might need to use is Object obj = cl.newInstance();
Let me know if still you got stucked somewhere.
I know this is an old topic but this feature has now been implemented since SQL Server 2017. The parameter you're looking for is FIELDQUOTE= which defaults to '"'. See more on https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql?view=sql-server-2017
As long as you specify a width on the element, it should wrap itself without needing anything else.
DocumentElement
is the root node of the document so childNodes[1]
doesn't exist in that document. childNodes[0]
would be the <Settings> node
I'm not totally satisfied with the other answers given. They've all got some kind of flaw to them.
Using keyPress
with event.which
is unreliable because you can't catch a backspace or a delete (as mentioned by Tarl).
Using keyDown
(as in Niva's and Tarl's answers) is a bit better, but the solution is flawed because it attempts to use event.keyCode
with String.fromCharCode()
(keyCode and charCode are not the same!).
However, what we DO have with the keydown
or keyup
event is the actual key that was pressed (event.key
).
As far as I can tell, any key
with a length of 1 is a character (number or letter) regardless of which language keyboard you're using. Please correct me if that's not true!
Then there's that very long answer from asdf. That might work perfectly, but it seems like overkill.
So here's a simple solution that will catch all characters, backspace, and delete. (Note: either keyup
or keydown
will work here, but keypress
will not)
$("input").keydown(function(event) {
var isWordCharacter = event.key.length === 1;
var isBackspaceOrDelete = event.keyCode === 8 || event.keyCode === 46;
if (isWordCharacter || isBackspaceOrDelete) {
// do something
}
});
Since beta.16 the parameters are not passed as array to the transform()
method anymore but instead as individual parameters:
{{ myData | date:'fullDate':'arg1':'arg2' }}
export class DatePipe implements PipeTransform {
transform(value:any, arg1:any, arg2:any):any {
...
}
https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26
pipes now take a variable number of arguments, and not an array that contains all arguments.
You could target all text boxes with input[type=text]
and then explicitly define the class for the textboxes who need it.
You can code like below :
input[type=text] {_x000D_
padding: 0;_x000D_
height: 30px;_x000D_
position: relative;_x000D_
left: 0;_x000D_
outline: none;_x000D_
border: 1px solid #cdcdcd;_x000D_
border-color: rgba(0, 0, 0, .15);_x000D_
background-color: white;_x000D_
font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
width: 526px;_x000D_
margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
you can use below code to check for brokers available if server is running.
import org.I0Itec.zkclient.ZkClient;
public static boolean isBrokerRunning(){
boolean flag = false;
ZkClient zkClient = new ZkClient(endpoint.getZookeeperConnect(), 10000);//, kafka.utils.ZKStringSerializer$.MODULE$);
if(zkClient!=null){
int brokersCount = zkClient.countChildren(ZkUtils.BrokerIdsPath());
if(brokersCount > 0){
logger.info("Following Broker(s) {} is/are available on Zookeeper.",zkClient.getChildren(ZkUtils.BrokerIdsPath()));
flag = true;
}
else{
logger.error("ERROR:No Broker is available on Zookeeper.");
}
zkClient.close();
}
return flag;
}
One way to do this would be to pass the instance of ParentClass
to the ChildClass
on construction
public ChildClass
{
private ParentClass parent;
public ChildClass(ParentClass parent)
{
this.parent = parent;
}
public void LoadData(DateTable dt)
{
// do something
parent.CurrentRow++; // or whatever.
parent.UpdateProgressBar(); // Call the method
}
}
Make sure to pass the reference to this
when constructing ChildClass
inside parent:
if(loadData){
ChildClass childClass = new ChildClass(this); // here
childClass.LoadData(this.Datatable);
}
Caveat: This is probably not the best way to organise your classes, but it directly answers your question.
EDIT: In the comments you mention that more than 1 parent class wants to use ChildClass
. This is possible with the introduction of an interface, eg:
public interface IParentClass
{
void UpdateProgressBar();
int CurrentRow{get; set;}
}
Now, make sure to implement that interface on both (all?) Parent Classes and change child class to this:
public ChildClass
{
private IParentClass parent;
public ChildClass(IParentClass parent)
{
this.parent = parent;
}
public void LoadData(DateTable dt)
{
// do something
parent.CurrentRow++; // or whatever.
parent.UpdateProgressBar(); // Call the method
}
}
Now anything that implements IParentClass
can construct an instance of ChildClass
and pass this
to its constructor.
I believe the problem is that codecs.BOM_UTF8
is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!"
Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8:
import codecs
file = codecs.open("lol", "w", "utf-8")
file.write(u'\ufeff')
file.close()
(That seems to give the right answer - a file with bytes EF BB BF.)
EDIT: S. Lott's suggestion of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before.
Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable
Type in command line
echo %JAVA_HOME%
and
java -version
To verify whether your installation was done successfully.
This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.
Steps to resolve:
Open the Run window:
Press windows+R
Open registry window:
Type regedit
and enter.
Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\
If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.
For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:
Create a new subkey of 1.8.
For 1.8 create a String Key with name JavaHome with the value of JRE home:
Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html
Like Vatine wrote: Since go lacks generics it would have to be part of the language and not the standard library. For that you would then have to pollute the language with keywords set, union, intersection, difference, subset...
The other reason is, that it's not clear at all what the "right" implementation of a set is:
There is a functional approach:
func IsInEvenNumbers(n int) bool {
if n % 2 == 0 {
return true
}
return false
}
This is a set of all even ints. It has a very efficient lookup and union, intersect, difference and subset can easily be done by functional composition.
A map does not have that problem, since you store something associated with the value.
Although @dunedin15's fantastic answer has served me well on a number of occasions, it can give inaccurate results for some edge-cases, such as when debugging build settings of a static lib for an Archive build.
As an alternative, a Run Script Build Phase can be easily added to any target to “Log Build Settings” when it's built:
To add, (with the target in question selected) under the Build Phases tab-section click the little ? button a dozen-or-so pixels up-left-ward from the Target Dependencies section, and set the shell to /bin/bash
and the command to export
. You'll also probably want to drag the phase upwards so that it happens just after Target Dependencies and before Copy Headers or Compile Sources. Renaming the phase from “Run Script” to “Log Build Settings” isn't a bad idea.
The result is this incredibly helpful listing of current environment variables used for building:
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
}
Here's an example that uses the class:
try {
// Generate a temporary key. In practice, you would save this key.
// See also Encrypting with DES Using a Pass Phrase.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter(key);
// Encrypt
String encrypted = encrypter.encrypt("Don't tell anybody!");
// Decrypt
String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}
Open up your file using regular old vanilla Notepad that comes with Windows.
It will show you the encoding of the file when you click "Save As...".
It'll look like this:
Whatever the default-selected encoding is, that is what your current encoding is for the file.
If it is UTF-8, you can change it to ANSI and click save to change the encoding (or visa-versa).
I realize there are many different types of encoding, but this was all I needed when I was informed our export files were in UTF-8 and they required ANSI. It was a onetime export, so Notepad fit the bill for me.
FYI: From my understanding I think "Unicode" (as listed in Notepad) is a misnomer for UTF-16.
More here on Notepad's "Unicode" option: Windows 7 - UTF-8 and Unicdoe
other method
INSERT INTO tableName (col1, col2, col3, col4, col5)
select * from table(
values
(val1, val2, val3, val4, val5),
(val1, val2, val3, val4, val5),
(val1, val2, val3, val4, val5),
(val1, val2, val3, val4, val5)
) tmp
In Eclipse: Ctrl + F8 -> SVN Repository Exploring -> Right Click in the respository -> Location Properties -> Finish ;)
I encountered the same problem to configure Git on a collaborative development platform that I have to manage.
To solve it :
I've Updated the release of Curl installed on the server. Download the last version on the website Download page of curland follow the installation proceedings Installation proceedings of curl
Get back the certificate of the authority which delivers the certificate for the server.
Add this certificate to the CAcert file used by curl. On my server it is located in /etc/pki/tls/certs/ca-bundle.crt
.
Configure git to use this certificate file by editing the .gitconfig file and set the sslcainfo path. sslcainfo= /etc/pki/tls/certs/ca-bundle.crt
On the client machine you must get the certificate and configure the .gitconfig file too.
I hope this will help some of you.
Edit .git/config
file under your repo directory
Find url=
entry under section [remote "origin"]
Change it from url=https://github.com/rootux/ms-Dropdown.git
to
https://[email protected]/rootux/ms-Dropdown.git
where USERNAME
is your github user name
It’s a common error and it can be easily fixed. This error message is an indication of that the file you are trying to import is larger than your web host allows
No data was received to import. Either no file name was submitted, or the file size exceeded the maximum size permitted by your PHP configuration. See FAQ 1.16.
Solution:
A solution is easy, Need to increase file size upload limit as per your requirement.
First of all, stop the XAMPP/Wamp and then find the php.ini
in the following locations. Windows: C:\xampp\php\php.ini
Open the php.ini
file. Find these lines in the php.ini
file and replace it following numbers
upload_max_filesize = 64M
And then restart your XAMPP/Wamp
NOTE: For Windows, you can find the file in the C:\xampp\php\php.ini-Folder (Windows) or in the etc-Folder (within the xampp-Folder)
You should be using a class
for multiple elements as an id
is meant to be only a single element. To answer your question on the .each()
syntax though, this is what it would look like:
$('#myID').each(function() {
$(this).remove();
});
Official JQuery documentation here.
Very good answer using inheritance, just remember to override the initializer
public class Utf8StringWriter : StringWriter
{
public Utf8StringWriter(StringBuilder sb) : base (sb)
{
}
public override Encoding Encoding { get { return Encoding.UTF8; } }
}
For Visual Studio Code:
launch.json
file"args": ["some argument", "another one"],
With the help of spark-csv we can write to a CSV file.
val dfsql = sqlContext.sql("select * from tablename")
dfsql.write.format("com.databricks.spark.csv").option("header","true").save("output.csv")`
Let me explain when to use FIND_IN_SET and When to use IN.
Let's take table A which has columns named "aid","aname". Let's take table B which has columns named "bid","bname","aids".
Now there are dummy values in Table A and Table B as below.
aid aname
1 Apple
2 Banana
3 Mango
bid bname aids
1 Apple 1,2
2 Banana 2,1
3 Mango 3,1,2
enter code here
Case1: if you want to get those records from table b which has 1 value present in aids columns then you have to use FIND_IN_SET.
Query: select * from A JOIN B ON FIND_IN_SET(A.aid,b.aids) where A.aid = 1 ;
Case2: if you want to get those records from table a which has 1 OR 2 OR 3 value present in aid columns then you have to use IN.
Query: select * from A JOIN B ON A.aid IN (b.aids);
Now here upto you that what you needs through mysql query.
Since Docker 1.5 you can now expose a range of ports to other linked containers using:
The Dockerfile EXPOSE command:
EXPOSE 7000-8000
or The Docker run command:
docker run --expose=7000-8000
Or instead you can publish a range of ports to the host machine via Docker run command:
docker run -p 7000-8000:7000-8000
For tcsh, I have to use the following command :
command >& file
If use command &> file
, it will give "Invalid null command" error.
Addressing an element of dictionary is like sitting on donkey and enjoy the ride.
As a rule of Python, a DICTIONARY is orderless
If there is
dic = {1: "a", 2: "aa", 3: "aaa"}
Now suppose if I go like dic[10] = "b"
, then it will not add like this always
dic = {1:"a",2:"aa",3:"aaa",10:"b"}
It may be like
dic = {1: "a", 2: "aa", 3: "aaa", 10: "b"}
Or
dic = {1: "a", 2: "aa", 10: "b", 3: "aaa"}
Or
dic = {1: "a", 10: "b", 2: "aa", 3: "aaa"}
Or any such combination.
So a rule of thumb is that a DICTIONARY is orderless!
One more thing node provides is the ability to create multiple v8 instanes of node using node's child process( childProcess.fork() each requiring 10mb memory as per docs) on the fly, thus not affecting the main process running the server. So offloading a background job that requires huge server load becomes a child's play and we can easily kill them as and when needed.
I've been using node a lot and in most of the apps we build, require server connections at the same time thus a heavy network traffic. Frameworks like Express.js and the new Koajs (which removed callback hell) have made working on node even more easier.
if you want to find out the exact error go to the following path in your project: /app/build/reports/lint-results-release-fatal.html(or .xml). The easiest way is if you go to the xml file, it will show you exactly what the error is including its position of the error in your either java class or xml file. Turning off the lint checks is not a good idea, they're there for a reason. Instead, go to:
/app/build/reports/lint-results-release-fatal.html or
/app/build/reports/lint-results-release-fatal.xml
and fix it.
To figure out what is the difference between before_action and before_filter, we should understand the difference between action and filter.
An action is a method of a controller to which you can route to. For example, your user creation page might be routed to UsersController#new - new is the action in this route.
Filters run in respect to controller actions - before, after or around them. These methods can halt the action processing by redirecting or set up common data to every action in the controller.
Rails 4 –> _action
Rails 3 –> _filter
dojox.grid.DataGrid offers a JS abstraction for data so you can hook it up to various backends with provided dojo.data stores or write your own. You'll obviously need one that supports random access for this many records. DataGrid also provides full accessibility.
Edit so here's a link to Matthew Russell's article that should provide the example you need, viewing millions of records with dojox.grid. Note that it uses the old version of the grid, but the concepts are the same, there were just some incompatible API improvements.
Oh, and it's totally free open source.
You might need to collect the stats as you go, but @@ROWCOUNT
captures this:
declare @Fish table (
Name varchar(32)
)
insert into @Fish values ('Cod')
insert into @Fish values ('Salmon')
insert into @Fish values ('Butterfish')
update @Fish set Name = 'LurpackFish' where Name = 'Butterfish'
select @@ROWCOUNT --gives 1
update @Fish set Name = 'Dinner'
select @@ROWCOUNT -- gives 3
I can't add comment because of reputation. add one more delegate need in @clearlight answer.
func textViewDidBeginEditing(_ textView: UITextView) {
cell.placeholderLabel.isHidden = !textView.text.isEmpty
}
is need
because textViewDidChange
is not called first time
In pointer to an integer if pointer is incremented then it goes next integer.
in array of pointer if pointer is incremented it jumps to next array
Credit should go here: how to detect if a link was clicked when window.onbeforeunload is triggered?
Basically, the solution adds a listener to detect if a link or window caused the unload event to fire.
var link_was_clicked = false;
document.addEventListener("click", function(e) {
if (e.target.nodeName.toLowerCase() === 'a') {
link_was_clicked = true;
}
}, true);
window.onbeforeunload = function(e) {
if(link_was_clicked) {
return;
}
return confirm('Are you sure?');
}
For nullable types ToString()
actually handles null
values:
int? i = null;
var s1 = i.ToString(); // returns ""
var s2 = Convert.ToString(i); // returns ""
Just to remedy the existing answers.
Source:
https://docs.microsoft.com/en-us/dotnet/api/system.nullable-1.tostring?view=net-5.0
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'
or simply this if you are sure that you have no values like this CKIT002
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
PostgreSQL supports regular expressions matching.
So, your example would look like
SELECT * FROM books WHERE title ~ '^\d+ ?'
This will match a title starting with one or more digits and an optional space
Windows 7 location is: C:\Users\All Users\MySQL\MySQL Server 5.5\my.ini
For XP may be: C:\Documents and Settings\All Users\MySQL\MySQL Server 5.5\my.ini
At the tops of these files are comments defining where my.cnf
can be found.
if you want to access table cell
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[1]"));
If you want to access nested table cell -
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[2]"+//table/tbody/tr[1]/td[2]));
For more details visit this Tutorial
This is the source code to the Guava library's Files.createTempDir(). It's nowhere as complex as you might think:
public static File createTempDir() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
String baseName = System.currentTimeMillis() + "-";
for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
File tempDir = new File(baseDir, baseName + counter);
if (tempDir.mkdir()) {
return tempDir;
}
}
throw new IllegalStateException("Failed to create directory within "
+ TEMP_DIR_ATTEMPTS + " attempts (tried "
+ baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')');
}
By default:
private static final int TEMP_DIR_ATTEMPTS = 10000;
Try this:
string callbackurl = Request.Url.Host != "localhost"
? Request.Url.Host : Request.Url.Authority;
This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.
They are used for different purposes and in fact have different operator precedences. The &&
and ||
operators are intended for Boolean conditions, whereas and
and or
are intended for control flow.
For example, the following is a Boolean condition:
if ($foo == $bar && $baz != $quxx) {
This differs from control flow:
doSomething() or die();
I'd like to offer this suggestion as a side note.
If you're looking to fix all the 'trailing whitespaces' warnings your linter
throws at you.
You can have VSCode automatically trim whitespaces from an entire file using
the keyboard chord.
CTRL+K / X (by default)
I was looking into showing whitespaces because my linter kept bugging me with whitespace warnings. So that's why I'm here.
JSX will evaluate JavaScript expressions in curly braces
In this case, this.props.removeTaskFunction(todo)
is invoked and the return value is assigned to onClick
What you have to provide for onClick
is a function. To do this, you can wrap the value in an anonymous function.
export const samepleComponent = ({todoTasks, removeTaskFunction}) => {
const taskNodes = todoTasks.map(todo => (
<div>
{todo.task}
<button type="submit" onClick={() => removeTaskFunction(todo)}>Submit</button>
</div>
);
return (
<div className="todo-task-list">
{taskNodes}
</div>
);
}
});
You can create user instances and have each app talk to its very own SQL Express.
There is no limit on the number of databases.
You can also use query(), i.e.:
df_filtered = df.query('a == 4 & b != 2')
Then there's the way of expressing your 'if' construct more tersely:
FOO='default'
[ -n "${VARIABLE}" ] && FOO=${VARIABLE}
So I found that if you are compiling from Visual Studios you just have to exclude the included .cpp file from the final build (that which you are extending from):
Visual Studios: .cpp file > right click > properties > configuration properties > general > excluded from build > yes
I believe you can also exclude the file when compiling from the command line.
It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.
A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?
Settings > Applications > Unknown sources...
Edit
Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive
Add the sheet name infront of the cell, e.g.:
=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")
Assumes the sheet name is "stock"
The align
attribute is deprecated. Use CSS text-align
instead. Also, the span will not center the text unless you use display:block
or display:inline-block
and set a value for the width, but then it will behave the same as a div (block element).
Can you post an example of your layout? Use www.jsfiddle.net
As of this writing, in OS X, it will usually look like this
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files
If you are a freak like me, and put your apps in ~/Applications
, then it will be
"/Users/yougohere/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files
If neither of those are working, then type chrome://version
in your Chrome address bar, and it will tell you what "command line" invocation you should be using. Just add --allow-file-access-from-files
to that.
If you are using spring with application.yml the following will work for you
spring:
datasource:
url: jdbc:h2:mem:mydb;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;INIT=CREATE SCHEMA IF NOT EXISTS calendar
Try Using JOptionPane or Swt Shell .
One use-case is that you have named (some of) your columns with some prefix, and you want the columns sorted with those prefixes all together and in some particular order (not alphabetical).
For example, you might start all of your features with Ft_
, labels with Lbl_
, etc, and you want all unprefixed columns first, then all features, then the label. You can do this with the following function (I will note a possible efficiency problem using sum
to reduce lists, but this isn't an issue unless you have a LOT of columns, which I do not):
def sortedcols(df, groups = ['Ft_', 'Lbl_'] ):
return df[ sum([list(filter(re.compile(r).search, list(df.columns).copy())) for r in (lambda l: ['^(?!(%s))' % '|'.join(l)] + ['^%s' % i for i in l ] )(groups) ], []) ]
If you want to redirect previous location or last request then you have to include user_agent
library:
$this->load->library('user_agent');
and then use at last in a function that you are using:
redirect($this->agent->referrer());
its working for me.
At least in SQL Server 2012, you can right click in the query window and select Query Options. From there you can select Include Headers for grid and/or text and have the Save As work the way you want it without restarting SSMS.
You'll still need to change it in Tools->Options in the menu bar to have new query windows use those settings by default.
Use the following select statement to get the whole definition:
select ROUTINE_DEFINITION
from INFORMATION_SCHEMA.ROUTINES
where ROUTINE_NAME = 'someprocname'
I guess that SSMS and other tools read this out and make changes where necessary, such as changing CREATE to ALTER. As far as I know, SQL stores not other representations of the procedure.
The most beginner-friendly solution is:
Drag a Timer from the Toolbox, give it a Name, set your desired Interval, and set "Enabled" to True. Then double-click the Timer and Visual Studio (or whatever you are using) will write the following code for you:
private void wait_Tick(object sender, EventArgs e)
{
refreshText(); // Add the method you want to call here.
}
No need to worry about pasting it into the wrong code block or something like that.
Here is the full code with no errors
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
#map-canvas
{
height: 400px;
width: 500px;
}
</style>
</script>
<script type="text/javascript">
function initialize() {
var myLatLng = new google.maps.LatLng( 17.3850, 78.4867 ),
myOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ),
marker = new google.maps.Marker( {icon: {
url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
// This marker is 20 pixels wide by 32 pixels high.
size: new google.maps.Size(20, 32),
// The origin for this image is (0, 0).
origin: new google.maps.Point(0, 0),
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(0, 32)
}, position: myLatLng, map: map} );
marker.setMap( map );
moveBus( map, marker );
}
function moveBus( map, marker ) {
setTimeout(() => {
marker.setPosition( new google.maps.LatLng( 12.3850, 77.4867 ) );
map.panTo( new google.maps.LatLng( 17.3850, 78.4867 ) );
}, 1000)
};
</script>
</head>
<body onload="initialize()">
<script type="text/javascript">
//moveBus();
</script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=AIzaSyB-W_sLy7VzaQNdckkY4V5r980wDR9ldP4"></script>
<div id="map-canvas" style="height: 500px; width: 500px;"></div>
</body>
</html>
Use this:
int get_lines(string file)
{
var lineCount = 0;
using (var stream = new StreamReader(file))
{
while (stream.ReadLine() != null)
{
lineCount++;
}
}
return lineCount;
}
Check that the date you are trying to set it to lies within the allowed date range if the minDate or maxDate options are set.
I found this script somewhere. I don't remember where, but it works for me:
#!/bin/ksh
line='---------------------------------------------'
pids=$(/usr/bin/ps -ef | sed 1d | awk '{print $2}')
if [ $# -eq 0 ]; then
read ans?"Enter port you would like to know pid for: "
else
ans=$1
fi
for f in $pids
do
/usr/proc/bin/pfiles $f 2>/dev/null | /usr/xpg4/bin/grep -q "port: $ans"
if [ $? -eq 0 ]; then
echo $line
echo "Port: $ans is being used by PID:\c"
/usr/bin/ps -ef -o pid -o args | egrep -v "grep|pfiles" | grep $f
fi
done
exit 0
Edit: Here is the original source: [Solaris] Which process is bound to a given port ?
The layouts in /res/layout are applied to both portrait and landscape, unless you specify otherwise. Let’s assume we have /res/layout/home.xml for our homepage and we want it to look differently in the 2 layout types.
CREATE TABLE [dbo].[VERSIONS](
[ID] [uniqueidentifier] NOT NULL,
[DATE] [varchar](100) NULL,
[SERVER] [varchar](100) NULL,
[DATABASE] [varchar](100) NULL,
[USER] [varchar](100) NULL,
[OBJECT] [varchar](100) NULL,
[ACTION] [varchar](100) NULL,
[CODE] [varchar](max) NULL,
CONSTRAINT [PK_VERSIONS] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[VERSIONS] ADD CONSTRAINT [DF_VERSIONS_ID] DEFAULT (newid()) FOR [ID]
GO
DROP TRIGGER [DB_VERSIONS_TRIGGER] ON ALL SERVER
CREATE TRIGGER [DB_VERSIONS_TRIGGER] ON ALL SERVER FOR CREATE_PROCEDURE, ALTER_PROCEDURE, DROP_PROCEDURE,
CREATE_TRIGGER, ALTER_TRIGGER, DROP_TRIGGER, CREATE_FUNCTION, ALTER_FUNCTION, DROP_FUNCTION, CREATE_VIEW, ALTER_VIEW,
DROP_VIEW, CREATE_TABLE, ALTER_TABLE, DROP_TABLE
AS
SET NOCOUNT ON SET XACT_ABORT OFF;
BEGIN
TRY
DECLARE @DATA XML = EVENTDATA()
DECLARE @SERVER VARCHAR(100) = @DATA.value('(EVENT_INSTANCE/ServerName)[1]','VARCHAR(100)')
DECLARE @DATABASE VARCHAR(100) = @DATA.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'VARCHAR(100)')
DECLARE @USER VARCHAR(100) = @DATA.value('(/EVENT_INSTANCE/LoginName)[1]','VARCHAR(100)')
DECLARE @OBJECT VARCHAR(100) = @DATA.value('(EVENT_INSTANCE/ObjectName)[1]','VARCHAR(100)')
DECLARE @ACTION VARCHAR(100) = @DATA.value('(/EVENT_INSTANCE/EventType)[1]','VARCHAR(100)')
DECLARE @CODE VARCHAR(MAX) = @DATA.value('(/EVENT_INSTANCE//TSQLCommand)[1]','VARCHAR(MAX)' )
IF OBJECT_ID('DB_VERSIONS.dbo.VERSIONS') IS NOT NULL
BEGIN
INSERT INTO [DB_VERSIONS].[dbo].[VERSIONS]([SERVER], [DATABASE], [USER], [OBJECT], [ACTION], [DATE], [CODE]) VALUES (@SERVER, @DATABASE, @USER, @OBJECT, @ACTION, getdate(), ISNULL(@CODE, 'NA'))
END
END
TRY
BEGIN
CATCH
END
CATCH
RETURN
I encountered the same problem today. I did heroku run rake db:migrate
though I migrated the model before, and the app doesn't crash.
you can set the types explicitly with pandas DataFrame.astype(dtype, copy=True, raise_on_error=True, **kwargs)
and pass in a dictionary with the dtypes you want to dtype
here's an example:
import pandas as pd
wheel_number = 5
car_name = 'jeep'
minutes_spent = 4.5
# set the columns
data_columns = ['wheel_number', 'car_name', 'minutes_spent']
# create an empty dataframe
data_df = pd.DataFrame(columns = data_columns)
df_temp = pd.DataFrame([[wheel_number, car_name, minutes_spent]],columns = data_columns)
data_df = data_df.append(df_temp, ignore_index=True)
In [11]: data_df.dtypes
Out[11]:
wheel_number float64
car_name object
minutes_spent float64
dtype: object
data_df = data_df.astype(dtype= {"wheel_number":"int64",
"car_name":"object","minutes_spent":"float64"})
now you can see that it's changed
In [18]: data_df.dtypes
Out[18]:
wheel_number int64
car_name object
minutes_spent float64
If you want to reset the window layout. Then
go to "WINDOW" -> "RESET WINDOW LAYOUT"
One, albeit a clumsy option to rearrange the columns when the column order must absolutely be changed, and foreign keys are in use, is to first dump the entire database with data, then dump just the schema (pg_dump -s databasename > databasename_schema.sql
). Next edit the schema file to rearrange the columns as you would like, then recreate the database from the schema, and finally restore the data into the newly created database.
OID's are still in use for Postgres with large objects (though some people would argue large objects are not generally useful anyway). They are also used extensively by system tables. They are used for instance by TOAST which stores larger than 8KB BYTEA's (etc.) off to a separate storage area (transparently) which is used by default by all tables. Their direct use associated with "normal" user tables is basically deprecated.
The oid type is currently implemented as an unsigned four-byte integer. Therefore, it is not large enough to provide database-wide uniqueness in large databases, or even in large individual tables. So, using a user-created table's OID column as a primary key is discouraged. OIDs are best used only for references to system tables.
Apparently the OID sequence "does" wrap if it exceeds 4B 6. So in essence it's a global counter that can wrap. If it does wrap, some slowdown may start occurring when it's used and "searched" for unique values, etc.
See also https://wiki.postgresql.org/wiki/FAQ#What_is_an_OID.3F
The solution by "Mark Seagoe" worked for me too. I got a message that "Port 443 in use by Unable to open process with PID 14508". So i opened task manager and killed this process 14508. This was used by my previous xampp version and it was orphaned.
so no need to change any ports or anything, this is a simple two step process and it worked .
Your server process has received a SIGPIPE
writing to a socket. This usually happens when you write to a socket fully closed on the other (client) side. This might be happening when a client program doesn't wait till all the data from the server is received and simply closes a socket (using close
function).
In a C program you would normally try setting to ignore SIGPIPE
signal or setting a dummy signal handler for it. In this case a simple error will be returned when writing to a closed socket. In your case a python seems to throw an exception that can be handled as a premature disconnect of the client.
In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.
decodeURI(window.location.search)
.replace('?', '')
.split('&')
.map(param => param.split('='))
.reduce((values, [ key, value ]) => {
values[ key ] = value
return values
}, {})
This is because keypress
events are fired before the new character is added to the value
of the element (so the first keypress
event is fired before the first character is added, while the value
is still empty). You should use keyup
instead, which is fired after the character has been added.
Note that, if your element #dSuggest
is the same as input:text[name=dSuggest]
you can simplify this code considerably (and if it isn't, having an element with a name that is the same as the id
of another element is not a good idea).
$('#dSuggest').keypress(function() {
var dInput = this.value;
console.log(dInput);
$(".dDimension:contains('" + dInput + "')").css("display","block");
});
Try this
sudo apt-get install postgresql postgresql-contrib libpq-dev
You should install PG Database server in the first place to install clients. Afterwards, you install clients.
The following code should display the time detla...
from datetime import datetime
tstart = datetime.now()
# code to speed test
tend = datetime.now()
print tend - tstart
This code is working fine for me in a loop
$remove = array(
"market_value",
"sector_id"
);
foreach($remove as $key){
unset($obj_name->$key);
}
IMO the nicest way is to use the next()
function:
router.get('/', function(req, res, next) {
var err = new Error('Not found');
err.status = 404;
return next(err);
}
Then the error is handled by your error handler and you can style the error nicely using HTML.
uncompress the zip HibernateTools-3.2.4.Beta1-R20081031133 later in eclipse --> menu Help -> Update Sofwate -> add site -> local add, and select de folder uncompress an install automatic
My problem was that I'm building a website which uses a lot of image-icons that have to be swapped by a different image on hover (e.g. blue-ish images turn red-ish on hover). I produced the following solution for this:
.container div {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-size: 100px 100px;_x000D_
}_x000D_
.container:hover .withoutHover {_x000D_
display: none;_x000D_
}_x000D_
.container .withHover {_x000D_
display: none;_x000D_
}_x000D_
.container:hover .withHover {_x000D_
display: block;_x000D_
}
_x000D_
<p>Hover the image to see it switch with the other. Note that I deliberately used inline CSS because I decided it was the easiest and clearest solution for my problem that uses more of these image pairs (with different URL's)._x000D_
</p>_x000D_
<div class=container>_x000D_
<div class=withHover style="background-image: url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQrqRsWFJ3492s0t0NmPEcpTQYTqNnH188R606cLOHm8H2pUGlH')"></div>_x000D_
<div class=withoutHover style="background-image: url('http://i.telegraph.co.uk/multimedia/archive/03523/Cat-Photo-Bombs-fa_3523609b.jpg')"></div>_x000D_
</div>
_x000D_
I introduced a container containing the pair of images. The first is visible and the other is hidden (display:none). When hovering the container, the first becomes hidden (display:none) and the second shows up again (display:block).
When you create a String, you can think of it as a list of char's, this means that for each character in your String, you need to support all the possible values of char. From the sun docs
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
If you have a reduced set of characters you want to support you can write a simple compression algorithm, which is analogous to binary->decimal->hex radix converstion. You go from 65,536 (or however many characters your target system supports) to 26 (alphabetical) / 36 (alphanumeric) etc.
I've used this trick a few times, for example encoding timestamps as text (target 36 +, source 10) - just make sure you have plenty of unit tests!
<a target="_blank" title="Share this page" href="http://www.sharethis.com/share?url=[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src="http://w.sharethis.com/images/share-classic.gif"></a>
Instructions
First, insert these lines wherever you want within your newsletter code. Then:
If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.
In case you came here looking for a way to modify logging of any (possibly deeply nested) module, use logging.Logger.manager.loggerDict
to get a dictionary of all of the logger objects. The returned names can then be used as the argument to logging.getLogger
:
import requests
import logging
for key in logging.Logger.manager.loggerDict:
print(key)
# requests.packages.urllib3.connectionpool
# requests.packages.urllib3.util
# requests.packages
# requests.packages.urllib3
# requests.packages.urllib3.util.retry
# PYREADLINE
# requests
# requests.packages.urllib3.poolmanager
logging.getLogger('requests').setLevel(logging.CRITICAL)
# Could also use the dictionary directly:
# logging.Logger.manager.loggerDict['requests'].setLevel(logging.CRITICAL)
Per user136036 in a comment, be aware that this method only shows you the loggers that exist at the time you run the above snippet. If, for example, a module creates a new logger when you instantiate a class, then you must put this snippet after creating the class in order to print its name.
SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS
(SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)
or
SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN
(SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)
or
SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B
ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL
Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.
In my case, I needed to add the JMETER_HOME
environment variable to be available via my Ant build scripts across all projects on my Jenkins server (Linux), in a way that would not interfere with my local build environment (Windows and Mac) in the build.xml
script. Setting the environment variable via Manage Jenkins - Configure System - Global properties was the easiest and least intrusive way to accomplish this. No plug-ins are necessary.
The environment variable is then available in Ant via:
<property environment="env" />
<property name="jmeter.home" value="${env.JMETER_HOME}" />
This can be verified to works by adding:
<echo message="JMeter Home: ${jmeter.home}"/>
Which produces:
JMeter Home: ~/.jmeter
This can be done from the command line. This will create a column for your image with a NOT NULL
property.
CREATE TABLE `test`.`pic` (
`idpic` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`caption` VARCHAR(45) NOT NULL,
`img` LONGBLOB NOT NULL,
PRIMARY KEY(`idpic`)
)
TYPE = InnoDB;
From here
yes, it may work in KITKAT.
above KITKAT+ it will go to internal storage:paths like(storage/emulated/0).
please think, how "Xender app" give permission to write in to external sd card.
So, Fortunately in Android 5.0 and later there is a new official way for apps to write to the external SD card. Apps must ask the user to grant write access to a folder on the SD card. They open a system folder chooser dialog. The user need to navigate into that specific folder and select it.
for more details, please refer https://metactrl.com/docs/sdcard-on-lollipop/
The warning message is because your "Type" variable was made a factor and "lunch" was not a defined level. Use the stringsAsFactors = FALSE
flag when making your data frame to force "Type" to be a character.
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
> str(fixed)
'data.frame': 3 obs. of 2 variables:
$ Type : Factor w/ 1 level "": NA 1 1
$ Amount: chr "100" "0" "0"
>
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3),stringsAsFactors=FALSE)
> fixed[1, ] <- c("lunch", 100)
> str(fixed)
'data.frame': 3 obs. of 2 variables:
$ Type : chr "lunch" "" ""
$ Amount: chr "100" "0" "0"
Just FYI, @
and its numpy equivalents dot
and matmul
are all equally fast. (Plot created with perfplot, a project of mine.)
Code to reproduce the plot:
import perfplot
import numpy
def setup(n):
A = numpy.random.rand(n, n)
x = numpy.random.rand(n)
return A, x
def at(data):
A, x = data
return A @ x
def numpy_dot(data):
A, x = data
return numpy.dot(A, x)
def numpy_matmul(data):
A, x = data
return numpy.matmul(A, x)
perfplot.show(
setup=setup,
kernels=[at, numpy_dot, numpy_matmul],
n_range=[2 ** k for k in range(15)],
)
The lattice
library is another good option. Here I've added a legend on the right side and jittered the points because some of them overlapped.
xyplot(Sepal.Width ~ Sepal.Length, group=Species, data=iris,
auto.key=list(space="right"),
jitter.x=TRUE, jitter.y=TRUE)
I use it all the time in my coding.
The -ansi
flag is equivalent to -std=c89
. As noted, it turns off some extensions of GCC. Adding -pedantic
turns off more extensions and generates more warnings. For example, if you have a string literal longer than 509 characters, then -pedantic
warns about that because it exceeds the minimum limit required by the C89 standard. That is, every C89 compiler must accept strings of length 509; they are permitted to accept longer, but if you are being pedantic, it is not portable to use longer strings, even though a compiler is permitted to accept longer strings and, without the pedantic warnings, GCC will accept them too.
I also had this problem. I was trying to enter data into the database without saving changes I had made in it. after i saved the changes worked
Thanks Chad! To show all the errors associated with the key, here's what I came up with. For some reason the base Html.ValidationMessage helper only shows the first error associated with the key.
<%= Html.ShowAllErrors(mykey) %>
HtmlHelper:
public static String ShowAllErrors(this HtmlHelper helper, String key) {
StringBuilder sb = new StringBuilder();
if (helper.ViewData.ModelState[key] != null) {
foreach (var e in helper.ViewData.ModelState[key].Errors) {
TagBuilder div = new TagBuilder("div");
div.MergeAttribute("class", "field-validation-error");
div.SetInnerText(e.ErrorMessage);
sb.Append(div.ToString());
}
}
return sb.ToString();
}
Play Store Rating
btn_rate_us.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
}
});
To Install bash you can do:
RUN apk add --update bash && rm -rf /var/cache/apk/*
If you do not want to add extra size to your image, you can use ash
or sh
that ships with alpine.
Reference: https://github.com/smebberson/docker-alpine/issues/43
You assign to big and small before the array is initialized, i.e., big and small assume the value of whatever is on the stack at this point. As they are just plain value types and no references, they won't assume a new value once values[0] is written to via cin >>.
Just move the assignment after your first loop and it should be fine.
Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following
#term-defs {
height: 300px;
overflow: scroll; }
This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.
#top {
position: fixed;
top: 0;
left: 0;
z-index: 999;
width: 100%;
height: 23px;
}
This will fix it to the top, on top of other content with a height of 23px.
The final implementation will depend on what effect you really want.
#include <thread>
#include <iostream>
#include <vector>
using namespace std;
void doSomething(int id) {
cout << id << "\n";
}
/**
* Spawns n threads
*/
void spawnThreads(int n)
{
std::vector<thread> threads(n);
// spawn n threads:
for (int i = 0; i < n; i++) {
threads[i] = thread(doSomething, i + 1);
}
for (auto& th : threads) {
th.join();
}
}
int main()
{
spawnThreads(10);
}
Just for the sake of any Googlers, if you're getting this error while building a Docker image, preface the failing RUN command with
apt-get update &&
This happens when Docker uses a cached image. Why the cached image wouldn't have the latest repo information the second time around is totally beyond me, but prefacing every single apt-get with an update does solve the problem.
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
As documented here: http://api.jquery.com/height/
Combined Solutions in Extensions class:
public static class Extensions {
public static byte[] ToByteArray(this object obj) {
var size = Marshal.SizeOf(data);
var bytes = new byte[size];
var ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(data, ptr, false);
Marshal.Copy(ptr, bytes, 0, size);
Marshal.FreeHGlobal(ptr);
return bytes;
}
public static string Serialize(this object obj) {
return JsonConvert.SerializeObject(obj);
}
}
If you want your own custom Error Logging you can easily write your own code. I'll give you a snippet from one of my projects.
public void SaveLogFile(object method, Exception exception)
{
string location = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\FolderName\";
try
{
//Opens a new file stream which allows asynchronous reading and writing
using (StreamWriter sw = new StreamWriter(new FileStream(location + @"log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
{
//Writes the method name with the exception and writes the exception underneath
sw.WriteLine(String.Format("{0} ({1}) - Method: {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), method.ToString()));
sw.WriteLine(exception.ToString()); sw.WriteLine("");
}
}
catch (IOException)
{
if (!File.Exists(location + @"log.txt"))
{
File.Create(location + @"log.txt");
}
}
}
Then to actually write to the error log just write (q
being the caught exception)
SaveLogFile(MethodBase.GetCurrentMethod(), `q`);
There is another difference to keep in mind between the two. With CSS, the :hover
state is always deactivated when the mouse moves off an element. However, with JavaScript, the onmouseout
event is not fired when the mouse moves off the element onto browser chrome rather than onto the rest of the page.
This happens more often than you might think, especially when you're making a navbar at the top of your page with custom hover states.
I realize this is old, but I got here from google and after reviewing the accepted answer I did my own statement and it worked for me hope someone will find it useful:
INSERT IGNORE INTO destTable SELECT id, field2,field3... FROM origTable
Edit: This works on MySQL I did not test on MSSQL
In addition to @Dan Herbert's answer , You we should encode just the values generally.
Split has params parameter Split('&','='); expression firstly split by & then '=' so odd elements are all values to be encoded shown below.
public static void EncodeQueryString(ref string queryString)
{
var array=queryString.Split('&','=');
for (int i = 0; i < array.Length; i++) {
string part=array[i];
if(i%2==1)
{
part=System.Web.HttpUtility.UrlEncode(array[i]);
queryString=queryString.Replace(array[i],part);
}
}
}
Install Mylyn connector for GitHub from this update site, it provides great integration: you can directly import your repositories using Import > Projects from Git > GitHub. You can set the default repository folder in Preferences > Git.
I had a similar problem and the solution was to do this:
#cloud-container{
position:absolute;
top:0;
bottom:0;
}
I wanted a page-centered div with height 100% of page height, so my total solution was:
#cloud-container{
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
width: XXXpx; /*otherwise div defaults to page width*/
margin: 0 auto; /*horizontally centers div*/
}
You might need to make a parent element (or simply 'body') have position: relative;
A "Login" grants the principal entry into the SERVER.
A "User" grants a login entry into a single DATABASE.
One "Login" can be associated with many users (one per database).
Each of the above objects can have permissions granted to it at its own level. See the following articles for an explanation of each
if you upgraded your Angular Version, you need to change the version of
@angular-devkit/build-angular
inside your
package.json
from your old version to the new angular build version upgraded.
I had upgraded to Angular 10, so i needed to go to https://www.npmjs.com/package/@angular-devkit/build-angular and check which is my version according to Angular 10.
In my case, i founded that the version needs to be 0.1001.7
, so i changed my old version to this version in my package.json and run
npm --save install
That was enough.
if you have already pushed your commit then. do
git checkout origin/<remote-branch> <filename>
git commit --amend
AND If you have not pushed the changes on the server you can use
git reset --soft HEAD~1
Using Laravel V 5.5.39 with Php 7.1.12 is working fine, but later (newer) php versions cause the problem. So, change Php version and you will get the solution 100% .
I am using ASP.NET MVC 4, and this what worked for me:
ControllerContext.Controller.ValueProvider.GetValue("controller").RawValue
ControllerContext.Controller.ValueProvider.GetValue("action").RawValue
value = (int)(value * 100 + 0.5) / 100.0;
Note: SYSDATE - returns only date, i.e., "yyyy-mm-dd" is not correct. SYSDATE returns the system date of the database server including hours, minutes, and seconds. For example:
SELECT SYSDATE FROM DUAL; will return output similar to the following: 12/15/2017 12:42:39 PM
You can get around the "impedance mismatch" caused by the lack of precision in the DateTimeField/date
object comparison -- that can occur if using range -- by using a datetime.timedelta to add a day to last date in the range. This works like:
start = date(2012, 12, 11)
end = date(2012, 12, 18)
new_end = end + datetime.timedelta(days=1)
ExampleModel.objects.filter(some_datetime_field__range=[start, new_end])
As discussed previously, without doing something like this, records are ignored on the last day.
Edited to avoid the use of datetime.combine
-- seems more logical to stick with date instances when comparing against a DateTimeField
, instead of messing about with throwaway (and confusing) datetime
objects. See further explanation in comments below.
contents in my backup_settings.ini file
[Settings]
year = 2020
python code for reading
import configparser
config = configparser.ConfigParser()
config.read('backup_settings.ini') #path of your .ini file
year = config.get("Settings","year")
print(year)
for writing or updating
from pathlib import Path
import configparser
myfile = Path('backup_settings.ini') #Path of your .ini file
config.read(myfile)
config.set('Settings', 'year','2050') #Updating existing entry
config.set('Settings', 'day','sunday') #Writing new entry
config.write(myfile.open("w"))
output
[Settings]
year = 2050
day = sunday
Or you can execute in python console or in Jupyter Notebook:
import csv
data = open("file.csv","r")
data
You will see information about the data object like this:
<_io.TextIOWrapper name='arch.csv' mode='r' encoding='cp1250'>
As you can see it contains encoding infotmation.
Just add parameters, split by comma:
UPDATE tablename SET column1 = "value1", column2 = "value2" ....
See also: mySQL manual on UPDATE
Changing the memory_limit
by ini_set('memory_limit', '-1');
is not a proper solution. Please don't do that.
Your PHP code may have a memory leak somewhere and you are telling the server to just use all the memory that it wants. You wouldn't have fixed the problem at all. If you monitor your server, you will see that it is now probably using up most of the RAM and even swapping to disk.
You should probably try to track down the offending code in your code and fix it.
You may be able to adapt a version of the C++ virtual constructor idiom. As far as I know, C# doesn't support covariant return types. I believe that's on many peoples' wish lists.
Method 1
if($_FILES['cover_image']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}
Method 2
if($_FILES['cover_image']['size'] == 0) {
// No file was selected for upload, your (re)action goes here
}
onInputChange(evt) {
var tgt = evt.target || window.event.srcElement,
files = tgt.files;
if (FileReader && files && files.length) {
var fr = new FileReader();
fr.onload = function () {
var base64 = fr.result;
debugger;
}
fr.readAsDataURL(files[0]);
}
}
You can simply set the status code of the response to 200 like the following
public ActionResult SomeMethod(parameters...)
{
//others code here
...
Response.StatusCode = 200;
return YourObject;
}
Following codes will return list of names of the numeric columns of a data set.
cnames=list(marketing_train.select_dtypes(exclude=['object']).columns)
here marketing_train
is my data set and select_dtypes()
is function to select data types using exclude and include arguments and columns is used to fetch the column name of data set
output of above code will be following:
['custAge',
'campaign',
'pdays',
'previous',
'emp.var.rate',
'cons.price.idx',
'cons.conf.idx',
'euribor3m',
'nr.employed',
'pmonths',
'pastEmail']
Thanks
This code works well :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
var options = {};
$("#c").hide();
$("#d").hide();
$("#a").click(function(){
$("#c").toggle( "slide", options, 500 );
$("#d").hide();
});
$("#b").click(function(){
$("#d").toggle( "slide", options, 500 );
$("#c").hide();
});
});
</script>
<style>
nav{
float:left;
max-width:300px;
width:300px;
margin-top:100px;
}
article{
margin-top:100px;
height:100px;
}
#c,#d{
padding:10px;
border:1px solid olive;
margin-left:100px;
margin-top:100px;
background-color:blue;
}
button{
border:2px solid blue;
background-color:white;
color:black;
padding:10px;
}
</style>
</head>
<body>
<header>
<center>hi</center>
</header>
<nav>
<button id="a">Register 1</button>
<br>
<br>
<br>
<br>
<button id="b">Register 2</button>
</nav>
<article id="c">
<form>
<label>User name:</label>
<input type="text" name="123" value="something"/>
<br>
<br>
<label>Password:</label>
<input type="text" name="456" value="something"/>
</form>
</article>
<article id="d">
<p>Hi</p>
</article>
</body>
</html>
Reference:W3schools.com and jqueryui.com
Note:This is a example code don't forget to add all the script tags in order to achieve proper functioning of the code.
Assuming there are no prepending/succeeding whitespace characters, there are still a few ways to assert string equality. Some of those are:
strings.ToLower(..)
then ==
strings.EqualFold(.., ..)
cases#Lower
paired with ==
cases#Fold
paired with ==
Here are some basic benchmark results (in these tests, strings.EqualFold(.., ..)
seems like the most performant choice):
goos: darwin
goarch: amd64
BenchmarkStringOps/both_strings_equal::equality_op-4 10000 182944 ns/op
BenchmarkStringOps/both_strings_equal::strings_equal_fold-4 10000 114371 ns/op
BenchmarkStringOps/both_strings_equal::fold_caser-4 10000 2599013 ns/op
BenchmarkStringOps/both_strings_equal::lower_caser-4 10000 3592486 ns/op
BenchmarkStringOps/one_string_in_caps::equality_op-4 10000 417780 ns/op
BenchmarkStringOps/one_string_in_caps::strings_equal_fold-4 10000 153509 ns/op
BenchmarkStringOps/one_string_in_caps::fold_caser-4 10000 3039782 ns/op
BenchmarkStringOps/one_string_in_caps::lower_caser-4 10000 3861189 ns/op
BenchmarkStringOps/weird_casing_situation::equality_op-4 10000 619104 ns/op
BenchmarkStringOps/weird_casing_situation::strings_equal_fold-4 10000 148489 ns/op
BenchmarkStringOps/weird_casing_situation::fold_caser-4 10000 3603943 ns/op
BenchmarkStringOps/weird_casing_situation::lower_caser-4 10000 3637832 ns/op
Since there are quite a few options, so here's the code to generate benchmarks.
package main
import (
"fmt"
"strings"
"testing"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
func BenchmarkStringOps(b *testing.B) {
foldCaser := cases.Fold()
lowerCaser := cases.Lower(language.English)
tests := []struct{
description string
first, second string
}{
{
description: "both strings equal",
first: "aaaa",
second: "aaaa",
},
{
description: "one string in caps",
first: "aaaa",
second: "AAAA",
},
{
description: "weird casing situation",
first: "aAaA",
second: "AaAa",
},
}
for _, tt := range tests {
b.Run(fmt.Sprintf("%s::equality op", tt.description), func(b *testing.B) {
for i := 0; i < b.N; i++ {
benchmarkStringEqualsOperation(tt.first, tt.second, b)
}
})
b.Run(fmt.Sprintf("%s::strings equal fold", tt.description), func(b *testing.B) {
for i := 0; i < b.N; i++ {
benchmarkStringsEqualFold(tt.first, tt.second, b)
}
})
b.Run(fmt.Sprintf("%s::fold caser", tt.description), func(b *testing.B) {
for i := 0; i < b.N; i++ {
benchmarkStringsFoldCaser(tt.first, tt.second, foldCaser, b)
}
})
b.Run(fmt.Sprintf("%s::lower caser", tt.description), func(b *testing.B) {
for i := 0; i < b.N; i++ {
benchmarkStringsLowerCaser(tt.first, tt.second, lowerCaser, b)
}
})
}
}
func benchmarkStringEqualsOperation(first, second string, b *testing.B) {
for n := 0; n < b.N; n++ {
_ = strings.ToLower(first) == strings.ToLower(second)
}
}
func benchmarkStringsEqualFold(first, second string, b *testing.B) {
for n := 0; n < b.N; n++ {
_ = strings.EqualFold(first, second)
}
}
func benchmarkStringsFoldCaser(first, second string, caser cases.Caser, b *testing.B) {
for n := 0; n < b.N; n++ {
_ = caser.String(first) == caser.String(second)
}
}
func benchmarkStringsLowerCaser(first, second string, caser cases.Caser, b *testing.B) {
for n := 0; n < b.N; n++ {
_ = caser.String(first) == caser.String(second)
}
}
//Do this
int IS_NULL_PTR(char *k){
memset(&k, k, sizeof k);
if(k) { return 71; } ;
return 72;
}
int PRINT_PTR_SAFE(char *KR){
char *E=KR;;
if (IS_NULL_PTR(KR)==71){
printf("%s\r\n",KR);
} else {
printf("%s","(null)\r\n");
}
}
int main(int argc,char *argv[]){
int i=0;
char *A=malloc(sizeof(char)*9);
;strcpy(A,"hello world");
for (i=((int)(A))-10;i<1e+40;i++){
PRINT_PTR_SAFE(i);
}
}
//Then watch the show!
//Edit as you wish. Just credit me if you really want more of this.
If someone is looking to sub out more than a comma I'm a fan of:
"1,200".chars.grep(/\d/).join.to_i
dunno about performance but, it is more flexible than a gsub
, ie:
"1-200".chars.grep(/\d/).join.to_i
That was my case. It actually links to question #4485874, but I'm going to explain it here shortly.
When you try to require path/to/script.php?parameter=value
, PHP looks for file named script.php?parameter=value
, because UNIX allows you to have paths like this.
If you are really need to pass some data to included script, just declare it as $variable=...
or $GLOBALS[]=...
or other way you like.
If you desire to use Python 3, you can use the following:
import json
import urllib.request
req = urllib.request.Request('url')
with urllib.request.urlopen(req) as response:
result = json.loads(response.readall().decode('utf-8'))
find out commit id
git reflog
recover local branch you deleted by mistake
git branch need-recover-branch-name commitId
push need-recover-branch-name again if you deleted remote branch too before
git push origin need-recover-branch-name
int(limit)
returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).
Do this instead:
limit = int(limit)
Or when definiting limit
:
if 'limit' in user_data :
limit = int(user_data['limit'])