xcopy "%userprofile%\Desktop\?????????" "D:\Backup\" /s/h/e/k/f/c
should work, assuming that your language setting allows Cyrillic (or you use Unicode fonts in the console).
For reference about the arguments: http://ss64.com/nt/xcopy.html
I think we can write like this : $this->db->where('accommodation >=', minvalue); $this->db->where('accommodation <=', maxvalue);
//without dollar($) sign It's work for me :)
I can think of 2 ways to achieve this:
IFNULL():
The IFNULL() function returns a specified value if the expression is NULL.If the expression is NOT NULL, this function returns the expression.
Syntax:
IFNULL(expression, alt_value)
Example of IFNULL() with your query:
SELECT AVG( price )
FROM(
SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
WHERE listing_Type = 'AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
AND IFNULL( price, 0 ) > ( SELECT AVG( IFNULL( price, 0 ) )* 0.50
FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
FROM web_price_scan
WHERE listing_Type='AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
) g
WHERE cume_dist < 0.50
)
AND IFNULL( price, 0 ) < ( SELECT AVG( IFNULL( price, 0 ) ) *2
FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
FROM web_price_scan
WHERE listing_Type='AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
) d
WHERE cume_dist < 0.50)
)s
HAVING COUNT(*) > 5
COALESCE()
The COALESCE() function returns the first non-null value in a list.
Syntax:
COALESCE(val1, val2, ...., val_n)
Example of COALESCE() with your query:
SELECT AVG( price )
FROM(
SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
WHERE listing_Type = 'AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
FROM web_price_scan
WHERE listing_Type='AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
) g
WHERE cume_dist < 0.50
)
AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
FROM web_price_scan
WHERE listing_Type='AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
) d
WHERE cume_dist < 0.50)
)s
HAVING COUNT(*) > 5
One special case: a cookie has no path.
In this case set path as cookie.setPath(request.getRequestURI())
The javascript sets cookie without path so the browser shows it as cookie for the current page only. If I try to send the expired cookie with path == /
the browser shows two cookies: one expired with path == /
and another one with path == current page
.
This works for me without throwing an exception:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date parsed = format.parse("20110210");
java.sql.Date sql = new java.sql.Date(parsed.getTime());
}
}
Select's default value should be one of its value in the list. In order to load the select with default value you can use ng-options. A scope variable need to be set in the controller and that variable is assigned as ng-model in HTML's select tag.
View this plunker for any references:
Very easy to use select option submit
<select name="sortby" onchange="this.form.submit()">
<option value="">Featured</option>
<option value="asc" >Price: Low to High</option>
<option value="desc">Price: High to Low</option>
</select>
This code use and enjoy now:
Read More: Go Link
using @inexistent_function_call();
in your code will cause the intepreter to quietly die and abort the script parsing. You should check for invalid functions and try not to use the error-supressing operator(the @ char )
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)
}
}
You have to use the android:hint attribute
<EditText
android:id="@+id/message"
android:hint="<<Your placeholder>>"
/>
In Android Studio, you can switch from XML -> Design View and click on the Component in the layout, the EditText field in this case. This will show all the applicable attributes for that GUI component. This will be handy when you don't know about all the attributes that are there.
You would be surprised to see that EditText has more than 140 attributes for customization.
Fully fleshed out example with arrows for only the red edges:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_edges_from(
[('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])
val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}
values = [val_map.get(node, 0.25) for node in G.nodes()]
# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]
# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'),
node_color = values, node_size = 500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()
With Java 7 you can use the following class:
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
public class MyFileIterator extends SimpleFileVisitor<Path>
{
public MyFileIterator(String path) throws Exception
{
Files.walkFileTree(Paths.get(path), this);
}
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attributes) throws IOException
{
System.out.println("File: " + file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attributes) throws IOException
{
System.out.println("Dir: " + dir);
return FileVisitResult.CONTINUE;
}
}
Solved for me by setting my git client (GitExtensions) to always run in admin mode.
If you are using Java 8, use the code below.
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
httpConn.setRequestProperty ("Authorization", "Basic "+basicAuth);
The following works for me even with FK constraints, and combines the following answers to only drop the specified tables:
USE [YourDB];
DECLARE @TransactionName varchar(20) = 'stopdropandroll';
BEGIN TRAN @TransactionName;
set xact_abort on; /* automatic rollback https://stackoverflow.com/a/1749788/1037948 */
-- ===== DO WORK // =====
-- dynamic sql placeholder
DECLARE @SQL varchar(300);
-- LOOP: https://stackoverflow.com/a/10031803/1037948
-- list of things to loop
DECLARE @delim char = ';';
DECLARE @foreach varchar(MAX) = 'Table;Names;Separated;By;Delimiter' + @delim + 'AnotherName' + @delim + 'Still Another';
DECLARE @token varchar(MAX);
WHILE len(@foreach) > 0
BEGIN
-- set current loop token
SET @token = left(@foreach, charindex(@delim, @foreach+@delim)-1)
-- ======= DO WORK // ===========
-- dynamic sql (parentheses are required): https://stackoverflow.com/a/989111/1037948
SET @SQL = 'DELETE FROM [' + @token + ']; DBCC CHECKIDENT (''' + @token + ''',RESEED, 0);'; -- https://stackoverflow.com/a/11784890
PRINT @SQL;
EXEC (@SQL);
-- ======= // END WORK ===========
-- continue loop, chopping off token
SET @foreach = stuff(@foreach, 1, charindex(@delim, @foreach+@delim), '')
END
-- ===== // END WORK =====
-- review and commit
SELECT @@TRANCOUNT as TransactionsPerformed, @@ROWCOUNT as LastRowsChanged;
COMMIT TRAN @TransactionName;
Note:
I think it still helps to declare the tables in the order you want them deleted (i.e. kill dependencies first). As seen in this answer, rather than loop specific names you could substitute all tables with
EXEC sp_MSForEachTable 'DELETE FROM ?; DBCC CHECKIDENT (''?'',RESEED, 0);';
Yes it has, you can do it like this:
var str = " this is the answer "
str = str.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
print(srt) // "this is the answer"
CharacterSet is actually a really powerful tool to create a trim rule with much more flexibility than a pre defined set like .whitespacesAndNewlines has.
For Example:
var str = " Hello World !"
let cs = CharacterSet.init(charactersIn: " !")
str = str.trimmingCharacters(in: cs)
print(str) // "Hello World"
Try details: use any option..
MessageBox.Show("your message",
"window title",
MessageBoxButtons.OK,
MessageBoxIcon.Warning // for Warning
//MessageBoxIcon.Error // for Error
//MessageBoxIcon.Information // for Information
//MessageBoxIcon.Question // for Question
);
If you are caching information that you will ultimately want to "include" at a later point in time, you may want to try using var_export. That way you only take the hit in the "serialize" and not in the "unserialize".
Check for applicationIdSuffix
in your app's build.gradle file. See if it is concatenating any text to your applicationId
. If so, remove it.
Using Java 8's time API (assuming you are happy to get the year in your system's default time zone), you could use the Year::now
method:
int year = Year.now().getValue();
In the light of the latest httpoxy vulnerabilities, there is really a need for a full example, how to use HTTP_X_FORWARDED_FOR
properly.
So here is an example written in PHP, how to detect a client IP address, if you know that client may be behind a proxy and you know this proxy can be trusted. If you don't known any trusted proxies, just use REMOTE_ADDR
<?php
function get_client_ip ()
{
// Nothing to do without any reliable information
if (!isset ($_SERVER['REMOTE_ADDR'])) {
return NULL;
}
// Header that is used by the trusted proxy to refer to
// the original IP
$proxy_header = "HTTP_X_FORWARDED_FOR";
// List of all the proxies that are known to handle 'proxy_header'
// in known, safe manner
$trusted_proxies = array ("2001:db8::1", "192.168.50.1");
if (in_array ($_SERVER['REMOTE_ADDR'], $trusted_proxies)) {
// Get the IP address of the client behind trusted proxy
if (array_key_exists ($proxy_header, $_SERVER)) {
// Header can contain multiple IP-s of proxies that are passed through.
// Only the IP added by the last proxy (last IP in the list) can be trusted.
$proxy_list = explode (",", $_SERVER[$proxy_header]);
$client_ip = trim (end ($proxy_list));
// Validate just in case
if (filter_var ($client_ip, FILTER_VALIDATE_IP)) {
return $client_ip;
} else {
// Validation failed - beat the guy who configured the proxy or
// the guy who created the trusted proxy list?
// TODO: some error handling to notify about the need of punishment
}
}
}
// In all other cases, REMOTE_ADDR is the ONLY IP we can trust.
return $_SERVER['REMOTE_ADDR'];
}
print get_client_ip ();
?>
decodeURIComponent(mystring);
you can get passed parameters by using this bit of code:
//parse URL to get values: var i = getUrlVars()["i"];
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
Or this one-liner to get the parameters:
location.search.split("your_parameter=")[1]
This problem is because the machine can't find the the correct ISAM (indexed sequential driver method) registered that Access needs.
It's probably because the machine doesn't have MSACeesss installed? I would make sure you have the latest version of Jet, and if it still doesn't work, find the file Msrd3x40.dll from one of the other machines, copy it somewhere to the Vista machine and call regsvr32 on it (in Admin mode) that should sort it out for you.
You can set the groupby
column to index
then using sum
with level
df.set_index(['Fruit','Name']).sum(level=[0,1])
Out[175]:
Number
Fruit Name
Apples Bob 16
Mike 9
Steve 10
Oranges Bob 67
Tom 15
Mike 57
Tony 1
Grapes Bob 35
Tom 87
Tony 15
Change
JSONObject objects = getArray.getJSONArray(i);
to
JSONObject objects = getArray.getJSONObject(i);
or to
JSONObject objects = getArray.optJSONObject(i);
depending on which JSON-to/from-Java library you're using. (It looks like getJSONObject
will work for you.)
Then, to access the string elements in the "objects" JSONObject
, get them out by element name.
String a = objects.get("A");
If you need the names of the elements in the JSONObject
, you can use the static utility method JSONObject.getNames(JSONObject)
to do so.
String[] elementNames = JSONObject.getNames(objects);
"Get the value for the first element and the value for the last element."
If "element" is referring to the component in the array, note that the first component is at index 0, and the last component is at index getArray.length() - 1
.
I want to iterate though the objects in the array and get thier component and thier value. In my example the first object has 3 components, the scond has 5 and the third has 4 components. I want iterate though each of them and get thier component name and value.
The following code does exactly that.
import org.json.JSONArray;
import org.json.JSONObject;
public class Foo
{
public static void main(String[] args) throws Exception
{
String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";
// "I want to iterate though the objects in the array..."
JSONObject outerObject = new JSONObject(jsonInput);
JSONObject innerObject = outerObject.getJSONObject("JObjects");
JSONArray jsonArray = innerObject.getJSONArray("JArray1");
for (int i = 0, size = jsonArray.length(); i < size; i++)
{
JSONObject objectInArray = jsonArray.getJSONObject(i);
// "...and get thier component and thier value."
String[] elementNames = JSONObject.getNames(objectInArray);
System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
for (String elementName : elementNames)
{
String value = objectInArray.getString(elementName);
System.out.printf("name=%s, value=%s\n", elementName, value);
}
System.out.println();
}
}
}
/*
OUTPUT:
3 ELEMENTS IN CURRENT OBJECT:
name=A, value=a
name=B, value=b
name=C, value=c
5 ELEMENTS IN CURRENT OBJECT:
name=D, value=d4
name=E, value=e5
name=A, value=a1
name=B, value=b2
name=C, value=c3
4 ELEMENTS IN CURRENT OBJECT:
name=D, value=dd
name=A, value=aa
name=B, value=bb
name=C, value=cc
*/
Follow these steps to begin using Angular Material.
Step 1: Install Angular Material
npm install --save @angular/material
Step 2: Animations
Some Material components depend on the Angular animations module in order to be able to do more advanced transitions. If you want these animations to work in your app, you have to install the @angular/animations
module and include the BrowserAnimationsModule in your app.
npm install --save @angular/animations
Then
import {BrowserAnimationsModule} from '@angular/platform browser/animations';
@NgModule({
...
imports: [BrowserAnimationsModule],
...
})
export class PizzaPartyAppModule { }
Step 3: Import the component modules
Import the NgModule for each component you want to use:
import {MdButtonModule, MdCheckboxModule} from '@angular/material';
@NgModule({
...
imports: [MdButtonModule, MdCheckboxModule],
...
})
export class PizzaPartyAppModule { }
be sure to import the Angular Material modules after Angular's BrowserModule, as the import order matters for NgModules
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MdCardModule} from '@angular/material';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
HomeComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MdCardModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 4: Include a theme
Including a theme is required to apply all of the core and theme styles to your application.
To get started with a prebuilt theme, include the following in your app's index.html:
<link href="../node_modules/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
guys try this is a perfect answer for this question:
<script>
$(function(){
$('.nav li a').filter(function(){return this.href==location.href}).parent().addClass('active').siblings().removeClass('active')
$('.nav li a').click(function(){
$(this).parent().addClass('active').siblings().removeClass('active')
})
})
</script>
_x000D_
the window
contains everything, so you can call window.screen
and window.document
to get those elements. Check out this fiddle, pretty-printing the contents of each object: http://jsfiddle.net/JKirchartz/82rZu/
You can also see the contents of the object in firebug/dev tools like this:
console.dir(window);
console.dir(document);
console.dir(screen);
window
is the root of everything, screen
just has screen dimensions, and document
is top DOM object. so you can think of it as window
being like a super-document
...
subprocess.call
Automatically waits , you can also use:
p1.wait()
If you're on Ubuntu, and all of the above has failed you, AppArmor is most likely to blame.
Here is a good guide how to fix it: https://www.digitalocean.com/community/tutorials/how-to-create-an-apparmor-profile-for-nginx-on-ubuntu-14-04
Long story short:
vi /etc/apparmor.d/nginx
Or
sudo aa-complain nginx
sudo service nginx restart
See everything working nicely... then
sudo aa-logprof
I still had problems with Nginx not being able to read error.log, even though it had all the permissions possible, including in Apparomor. I'm guessing it's got something to do with the order of the entries, or some interaction with Passenger or PHP-Fpm... I've run out of time to troubleshoot this and have gone back to Apache for now. (Apache performs much better too FYI.)
AppArmor just lets Nginx do whatever it wants if you just remove the profile:
rm /etc/apparmor.d/nginx
service apparmor reload
Shockingly, but hardly surprising, a lot of posts on fixing Nginx errors resorts to completely disabling SELinux or removing AppArmor. That's a bad idea because you lose protection from a whole lot of software. Just removing the Nginx profile is a better way to troubleshoot your config files. Once you know that the problem isn't in your Nginx config files, you can take the time to create a proper AppArmor profile.
Without an AppArmor profile, especially if you run something like Passenger too, I give your server about a month to get backdoored.
You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
You need to understand the difference between Web application context and root application context .
In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.
The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .
Read the spring reference here for spring mvc .
Use the apache commons-lang3 lib
import org.apache.commons.lang3.exception.ExceptionUtils;
//...
String[] ss = ExceptionUtils.getRootCauseStackTrace(e);
logger.error(StringUtils.join(ss, System.lineSeparator()));
Explicit conversion constructors (C++ only)
The explicit function specifier controls unwanted implicit type conversions. It can only be used in declarations of constructors within a class declaration. For example, except for the default constructor, the constructors in the following class are conversion constructors.
class A
{
public:
A();
A(int);
A(const char*, int = 0);
};
The following declarations are legal:
A c = 1;
A d = "Venditti";
The first declaration is equivalent to A c = A( 1 );
.
If you declare the constructor of the class as explicit
, the previous declarations would be illegal.
For example, if you declare the class as:
class A
{
public:
explicit A();
explicit A(int);
explicit A(const char*, int = 0);
};
You can only assign values that match the values of the class type.
For example, the following statements are legal:
A a1;
A a2 = A(1);
A a3(1);
A a4 = A("Venditti");
A* p = new A(1);
A a5 = (A)1;
A a6 = static_cast<A>(1);
<form enctype='multipart/form-data'>
<input onchange="alert(this.value); this.value=null; return false;" type='file'>
<br>
<input type='submit' value='Upload'>
</form>
this.value=null;
is only necessary for Chrome, Firefox will work fine just with return false;
Here is a FIDDLE
cast(REGEXP_REPLACE(NameNumber, '[^0-9]', '') as UNSIGNED)
there are some other tables you can clear out: documented here : https://dx3webs.com/blog/house-keeping-for-your-magento-database
hope this helps Andy
I have faced the same issue and also not using virtual environment. easy_install is working for me.
easy_install boto3
There is a little tool called sloccount to count the lines of code in a directory.
It should be noted that it does more than you want as it ignores empty lines/comments, groups the results per programming language and calculates some statistics.
$string = 'abc-123-xyz-789';
$exploded = explode('-', $string);
echo end($exploded);
EDIT::Finally got around to removing the E_STRICT issue
The MOST CORRECT answer to your question is...
#content > div:first-of-type { /* css */ }
This will apply the CSS to the first div that is a direct child of #content (which may or may not be the first child element of #content)
Another option:
#content > div:nth-of-type(1) { /* css */ }
Yes, it is called Short-circuit Evaluation.
If the validity of the boolean statement can be assured after part of the statement, the rest is not evaluated.
This is very important when some of the statements have side-effects.
array
is a slightly misleading name. For a dynamically allocated array of pointers, malloc
will return a pointer to a block of memory. You need to use Chess*
and not Chess[]
to hold the pointer to your array.
Chess *array = malloc(size * sizeof(Chess));
array[i] = NULL;
and perhaps later:
/* create new struct chess */
array[i] = malloc(sizeof(struct chess));
/* set up its members */
array[i]->size = 0;
/* etc. */
Well, i agree with the @Mishkin Berteig - Agile Coach answer. Using the form is the quick way to use the POST features.
Anyway, i see some mention about javascript, but no code. I have that for my own needs, which includes jquery for easy POST plus others.
Basically, using the driver.execute_script()
you can send any javascript, including Ajax queries.
#/usr/local/env/python
# -*- coding: utf8 -*-
# proxy is used to inspect data involved on the request without so much code.
# using a basic http written in python. u can found it there: http://voorloopnul.com/blog/a-python-proxy-in-less-than-100-lines-of-code/
import selenium
from selenium import webdriver
import requests
from selenium.webdriver.common.proxy import Proxy, ProxyType
jquery = open("jquery.min.js", "r").read()
#print jquery
proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = "127.0.0.1:3128"
proxy.socks_proxy = "127.0.0.1:3128"
proxy.ssl_proxy = "127.0.0.1:3128"
capabilities = webdriver.DesiredCapabilities.PHANTOMJS
proxy.add_to_capabilities(capabilities)
driver = webdriver.PhantomJS(desired_capabilities=capabilities)
driver.get("http://httpbin.org")
driver.execute_script(jquery) # ensure we have jquery
ajax_query = '''
$.post( "post", {
"a" : "%s",
"b" : "%s"
});
''' % (1,2)
ajax_query = ajax_query.replace(" ", "").replace("\n", "")
print ajax_query
result = driver.execute_script("return " + ajax_query)
#print result
#print driver.page_source
driver.close()
# this retuns that from the proxy, and is OK
'''
POST http://httpbin.org/post HTTP/1.1
Accept: */*
Referer: http://httpbin.org/
Origin: http://httpbin.org
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.0.0 Safari/538.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 7
Cookie: _ga=GAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; _gat=1
Connection: Keep-Alive
Accept-Encoding: gzip, deflate
Accept-Language: es-ES,en,*
Host: httpbin.org
None
a=1&b=2 <<---- that is OK, is the data contained into the POST
None
'''
You can duplicate a table without data by running:
CREATE TABLE x LIKE y;
(See the MySQL CREATE TABLE Docs)
You could write a script that takes the output from SHOW TABLES
from one database and copies the schema to another. You should be able to reference schema+table names like:
CREATE TABLE x LIKE other_db.y;
As far as the data goes, you can also do it in MySQL, but it's not necessarily fast. After you've created the references, you can run the following to copy the data:
INSERT INTO x SELECT * FROM other_db.y;
If you're using MyISAM, you're better off to copy the table files; it'll be much faster. You should be able to do the same if you're using INNODB with per table table spaces.
If you do end up doing an INSERT INTO SELECT
, be sure to temporarily turn off indexes with ALTER TABLE x DISABLE KEYS
!
EDIT Maatkit also has some scripts that may be helpful for syncing data. It may not be faster, but you could probably run their syncing scripts on live data without much locking.
In my case, the localhost url was redirected to https://localhost when I was debugging. This happened from one moment to other, without changing anything. I solved this by making a hard reload to the browser. Here the link
baos.toString(StandardCharsets.UTF_8);
Converts the buffer's contents into a string by decoding the bytes using the named charset.
The standard option grep -l
(that is a lowercase L) could do this.
From the Unix standard:
-l
(The letter ell.) Write only the names of files containing selected
lines to standard output. Pathnames are written once per file searched.
If the standard input is searched, a pathname of (standard input) will
be written, in the POSIX locale. In other locales, standard input may be
replaced by something more appropriate in those locales.
You also do not need -H
in this case.
One of the principal issues with pushing to a GIT is that the material you push will appear as your material, and will block submissions from other people on a team. As a GIT repository administrator, you will have to manage the hooks to prevent Alice's push from blocking Bob from pushing. To do that, you will want to ensure that your developers all belong to a group, lets call it 'developers' and that the repository is owned by root:developers, and then add this to the hooks/post-update script:
sudo chown -R root:developers $GIT_DIR
sudo chmod -R g+w $GIT_DIR
That will make it so that team members are able to push to the repository without stepping on each other's toes.
With React Hook, form is made super easy (React Hook Form: https://github.com/bluebill1049/react-hook-form)
i have reused your html markup.
import React from "react";
import useForm from 'react-hook-form';
function Test() {
const { useForm, register } = useForm();
const contactSubmit = data => {
console.log(data);
};
return (
<form name="contactform" onSubmit={contactSubmit}>
<div className="col-md-6">
<fieldset>
<input name="name" type="text" size="30" placeholder="Name" ref={register} />
<br />
<input name="email" type="text" size="30" placeholder="Email" ref={register} />
<br />
<input name="phone" type="text" size="30" placeholder="Phone" ref={register} />
<br />
<input name="address" type="text" size="30" placeholder="Address" ref={register} />
<br />
</fieldset>
</div>
<div className="col-md-6">
<fieldset>
<textarea name="message" cols="40" rows="20" className="comments" placeholder="Message" ref={register} />
</fieldset>
</div>
<div className="col-md-12">
<fieldset>
<button className="btn btn-lg pro" id="submit" value="Submit">
Send Message
</button>
</fieldset>
</div>
</form>
);
}
With ES6:
function test(a, b = 3) {
console.log(a, ' ', b);
}
test(1); // Output: 1 3
test(1, 2); // Output: 1 2
1 use eclipse bar to install a Mat plug-in to analyze, is a good choice. Studio Memory provides the Monitor 2.Android studio to display the memory occupancy of the application in real time.
IsEmpty()
would be the quickest way to check for that.
IsNull()
would seem like a similar solution, but keep in mind Null has to be assigned to the cell; it's not inherently created in the cell.
Also, you can check the cell by:
count()
counta()
Len(range("BCell").Value) = 0
If you are getting this instead:
Error: Template parse errors:
There is no directive with "exportAs" set to "ngModel"
Which was reported as a bug in github, then likely it is not a bug since you might:
[(ngModel)]]=
), ORformControlName
, with the ngModel
directive. This "has been deprecated in Angular v6 and will be removed in Angular v7", since this mixes both form strategies, making it:
seem like the actual
ngModel
directive is being used, but in fact it's an input/output property namedngModel
on the reactive form directive that simply approximates (some of) its behavior. Specifically, it allows getting/setting the value and intercepting value events. However, some ofngModel
's other features - like delaying updates withngModel
Options or exporting the directive - simply don't work (...)this pattern mixes template-driven and reactive forms strategies, which we generally don't recommend because it doesn't take advantage of the full benefits of either strategy. (...)
To update your code before v7, you'll want to decide whether to stick with reactive form directives (and get/set values using reactive forms patterns) or switch over to template-driven directives.
When you have an input like this:
<input formControlName="first" [(ngModel)]="value">
It will show a warning about mixed form strategies in the browser's console:
It looks like you're using
ngModel
on the same form field asformControlName
.
However, if you add the ngModel
as a value in a reference variable, example:
<input formControlName="first" #firstIn="ngModel" [(ngModel)]="value">
The error above is then triggered and no warning about strategy mixing is shown.
This test shows three blocks of two blocks together on the same line.
.group {
display:block;
box-sizing:border-box;
}
.group>div {
display:inline-block;
padding-bottom:4px;
}
.group>div>span,.group>div>div {
width:200px;
height:40px;
text-align: center;
padding-top:20px;
padding-bottom:0px;
display:inline-block;
border:1px solid black;
background-color:blue;
color:white;
}
input[type=text] {
height:1em;
}
_x000D_
<div class="group">
<div>
<span>First Name</span>
<span><input type="text"/></span>
</div>
<div>
<div>Last Name</div>
<div><input type="text"/></div>
</div>
<div>
<div>Address</div>
<div><input type="text"/></div>
</div>
</div>
_x000D_
package javaapplication4;
import java.text.*;
import java.util.*;
/**
*
* @author Stefan Wendelmann
*/
public class JavaApplication4
{
private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ParseException
{
SimpleDateFormat parser = new SimpleDateFormat("dd.MM.YYYY HH:mm:ss.SSS");
Date before = parser.parse("01.10.1990 07:00:00.000");
Date base = parser.parse("01.10.1990 08:00:00.000");
Date after = parser.parse("01.10.1990 09:00:00.000");
printCompare(base, base, "==");
printCompare(base, before, "==");
printCompare(base, before, "<");
printCompare(base, after, "<");
printCompare(base, after, ">");
printCompare(base, before, ">");
printCompare(base, before, "<=");
printCompare(base, base, "<=");
printCompare(base, after, "<=");
printCompare(base, after, ">=");
printCompare(base, base, ">=");
printCompare(base, before, ">=");
}
private static void printCompare (Date a, Date b, String operator){
System.out.println(sdf.format(b)+"\t"+operator+"\t"+sdf.format(a)+"\t"+compareTime(a, b, operator));
}
protected static boolean compareTime(Date a, Date b, String operator)
{
if (a == null)
{
return false;
}
try
{
//Zeit aus Datum holen
// The Magic happens here i only get the Time out of the Date Object
SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss.SSS");
a = parser.parse(parser.format(a));
b = parser.parse(parser.format(b));
}
catch (ParseException ex)
{
System.err.println(ex);
}
switch (operator)
{
case "==":
return b.compareTo(a) == 0;
case "<":
return b.compareTo(a) < 0;
case ">":
return b.compareTo(a) > 0;
case "<=":
return b.compareTo(a) <= 0;
case ">=":
return b.compareTo(a) >= 0;
default:
throw new IllegalArgumentException("Operator " + operator + " wird für Feldart Time nicht unterstützt!");
}
}
}
run:
08:00:00.000 == 08:00:00.000 true
07:00:00.000 == 08:00:00.000 false
07:00:00.000 < 08:00:00.000 true
09:00:00.000 < 08:00:00.000 false
09:00:00.000 > 08:00:00.000 true
07:00:00.000 > 08:00:00.000 false
07:00:00.000 <= 08:00:00.000 true
08:00:00.000 <= 08:00:00.000 true
09:00:00.000 <= 08:00:00.000 false
09:00:00.000 >= 08:00:00.000 true
08:00:00.000 >= 08:00:00.000 true
07:00:00.000 >= 08:00:00.000 false
BUILD SUCCESSFUL (total time: 0 seconds)
And for me the argument about whether an array should be sparse or not depends on the context.
For example, if $a[6][9] is not populated is the equivalent to $a[6][9] being populated with for example with "" or 0.
You can view the java doc examples or the example of usage of Predicate here
Basically it is used to filter rows in the resultset based on any specific criteria that you may have and return true for those rows that are meeting your criteria:
// the age column to be between 7 and 10
AgeFilter filter = new AgeFilter(7, 10, 3);
// set the filter.
resultset.beforeFirst();
resultset.setFilter(filter);
For me i was getting this error because i needed to put the arrays in paratheses. The error is a bit tricky in this case...
ie. concatenate((a, b))
is right
not concatenate(a, b)
hope that helps.
While using mysql version 8.0 + , use the following syntax to update root password after starting mysql daemon with --skip-grant-tables option
UPDATE user SET PASSWORD FOR 'root'@'localhost' = PASSWORD('your_new_password')
In a Spring Boot app, I used the following to get the file URL,
Thread.currentThread().getContextClassLoader().getResource("PromotionalOfferIdServiceV2.wsdl")
fwrite($handle, "<br>"."\r\n");
Add this under
$password = $_POST['password'].PHP_EOL;
this. .
useState is a hook that lets you add state to a functional component. It accepts an argument which is the initial value of the state property and returns the current value of state property and a method which is capable of updating that state property.
Following is a simple example:
import React, {useState} from react
function HookCounter {
const [count, stateCount]= useState(0)
return(
<div>
<button onClick{( ) => setCount(count+1)}> count{count}</button>
</div>
)
}
useState accepts the initial value of the state variable which is zero in this case and returns a pair of values. The current value of the state has been called count and a method that can update the state variable has been called as setCount.
I also faced the similar problem with JSON output format. This code worked for me with the above JSON format.
package com.test.ameba;
import java.util.List;
public class OutputRanges {
public List<Range> OutputRanges;
public String Message;
public String Entity;
/**
* @return the outputRanges
*/
public List<Range> getOutputRanges() {
return OutputRanges;
}
/**
* @param outputRanges the outputRanges to set
*/
public void setOutputRanges(List<Range> outputRanges) {
OutputRanges = outputRanges;
}
/**
* @return the message
*/
public String getMessage() {
return Message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
Message = message;
}
/**
* @return the entity
*/
public String getEntity() {
return Entity;
}
/**
* @param entity the entity to set
*/
public void setEntity(String entity) {
Entity = entity;
}
}
package com.test;
public class Range {
public String Name;
/**
* @return the name
*/
public String getName() {
return Name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
Name = name;
}
public Object[] Value;
/**
* @return the value
*/
public Object[] getValue() {
return Value;
}
/**
* @param value the value to set
*/
public void setValue(Object[] value) {
Value = value;
}
}
package com.test.ameba;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JSONTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String jsonString ="{\"OutputRanges\":[{\"Name\":\"ABF_MEDICAL_RELATIVITY\",\"Value\":[[1.3628407124839714]]},{\"Name\":\" ABF_RX_RELATIVITY\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_Unique_ID_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_FIRST_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_AMEBA_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_Effective_Date_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_AMEBA_MODEL\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_UC_ER_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_INN_OON_DED_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_COINSURANCE_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PCP_SPEC_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_INN_OON_OOP_MAX_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_IP_OP_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PHARMACY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PLAN_ADMIN_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]}],\"Message\":\"\",\"Entity\":null}";
ObjectMapper mapper = new ObjectMapper();
OutputRanges OutputRanges=null;
try {
OutputRanges = mapper.readValue(jsonString, OutputRanges.class);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("OutputRanges :: "+OutputRanges);;
System.out.println("OutputRanges.getOutputRanges() :: "+OutputRanges.getOutputRanges());;
for (Range r : OutputRanges.getOutputRanges()) {
System.out.println(r.getName());
}
}
}
var answer = Math.floor(x)
I sincerely hope this will help future searchers when googling for this common question.
$('#selector').is(':visible');
Here is pro example of using multi proptypes and single proptype.
import React, { Component } from 'react';
import { string, shape, array, oneOfType } from 'prop-types';
class MyComponent extends Component {
/**
* Render
*/
render() {
const { title, data } = this.props;
return (
<>
{title}
<br />
{data}
</>
);
}
}
/**
* Define component props
*/
MyComponent.propTypes = {
data: oneOfType([array, string, shape({})]),
title: string,
};
export default MyComponent;
Please reference :Spring Data JPA @Query, if you are using Spring Data JPA version 2.0.4 and later. Sample like below:
@Query(value = "SELECT u FROM User u ORDER BY id")
Page<User> findAllUsersWithPagination(Pageable pageable);
In Sql when any word contain @ sign it means it is variable and we use this variable to set value in it and use it on number area on the same sql script because it is only restricted on the single script while you can declare lot of variables of same type and name on many script. We use this variable in stored procedure lot because stored procedure are pre-compiled queries and we can pass values in these variable from script, desktop and websites for further information read Declare Local Variable, Sql Stored Procedure and sql injections.
Also read Protect from sql injection it will guide how you can protect your database.
Hope it help you to understand also any question comment me.
First Step you need to create a list instance through Arrays.asList();
String[] args = new String[]{"one","two","three"};
List<String> list = Arrays.asList(args);//it converts to immutable list
Then you need to pass 'list' instance to new ArrayList();
List<String> newList=new ArrayList<>(list);
A ClassCastException
ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example
Apple myApple = new Apple();
Fruit myFruit = (Fruit)myApple;
This works because an apple 'is a' fruit. However if we reverse this.
Fruit myFruit = new Fruit();
Apple myApple = (Apple)myFruit;
This will throw a ClasCastException because a Fruit is not (always) an Apple.
It is good practice to guard any explicit casts with an instanceof
check first:
if (myApple instanceof Fruit) {
Fruit myFruit = (Fruit)myApple;
}
Well, if you know where your user lives in the AD hierarchy (e.g. quite possibly in the "Users" container, if it's a small network), you could also bind to the user account directly, instead of searching for it.
DirectoryEntry deUser = new DirectoryEntry("LDAP://cn=John Doe,cn=Users,dc=yourdomain,dc=com");
if (deUser != null)
{
... do something with your user
}
And if you're on .NET 3.5 already, you could even use the vastly expanded System.DirectorySrevices.AccountManagement namespace with strongly typed classes for each of the most common AD objects:
// bind to your domain
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "LDAP://dc=yourdomain,dc=com");
// find the user by identity (or many other ways)
UserPrincipal user = UserPrincipal.FindByIdentity(pc, "cn=John Doe");
There's loads of information out there on System.DirectoryServices.AccountManagement - check out this excellent article on MSDN by Joe Kaplan and Ethan Wilansky on the topic.
Tracing helped me find what the problem was (Thank you Fabian for that suggestion). I found with further testing that I could get the client certificate to work on another server (Windows Server 2012). I was testing this on my development machine (Window 7) so I could debug this process. So by comparing the trace to an IIS Server that worked and one that did not I was able to pinpoint the relevant lines in the trace log. Here is a portion of a log where the client certificate worked. This is the setup right before the send
System.Net Information: 0 : [17444] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [17444] SecureChannel#54718731 - We have user-provided certificates. The server has not specified any issuers, so try all the certificates.
System.Net Information: 0 : [17444] SecureChannel#54718731 - Selected certificate:
Here is what the trace log looked like on the machine where the client certificate failed.
System.Net Information: 0 : [19616] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [19616] SecureChannel#54718731 - We have user-provided certificates. The server has specified 137 issuer(s). Looking for certificates that match any of the issuers.
System.Net Information: 0 : [19616] SecureChannel#54718731 - Left with 0 client certificates to choose from.
System.Net Information: 0 : [19616] Using the cached credential handle.
Focusing on the line that indicated the server specified 137 issuers I found this Q&A that seemed similar to my issue. The solution for me was not the one marked as an answer since my certificate was in the trusted root. The answer is the one under it where you update the registry. I just added the value to the registry key.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL
Value name: SendTrustedIssuerList Value type: REG_DWORD Value data: 0 (False)
After adding this value to the registry it started to work on my Windows 7 machine. This appears to be a Windows 7 issue.
I'm using n (Node version management)
You can install it in two ways
brew install n
or
npm install -g n
You can switch between different version of node and io. Here's an example from my current env when I call n without params:
$ n
io/3.3.1
node/0.12.7
node/4.0.0
node/5.0.0
? node/5.10.1
Save the execution file on your desktop Make sure you note the name of your file Go to start and type cmd right click on it
select run as administrator press enter
then you something below
C:\Users\your computer name\Desktop>
If you are seeing
C:\Windows\system32>
make sure you change it using CD
type the name of your file
C:\Users\your computer name\Desktop>the name of the file your copy.exe/ACTION=install /SKIPRULES=PerfMonCounterNotCorruptedCheck
Well, when writing it out to file, you do know what class T is, so you can store that in dump
. Then, when reading it back in, you can dynamically call it using reflection.
public JSONObject dump() throws JSONException {
JSONObject result = new JSONObject();
JSONArray a = new JSONArray();
for(T i : items){
a.put(i.dump());
// inside this i.dump(), store "class-name"
}
result.put("items", a);
return result;
}
public void load(JSONObject obj) throws JSONException {
JSONArray arrayItems = obj.getJSONArray("items");
for (int i = 0; i < arrayItems.length(); i++) {
JSONObject item = arrayItems.getJSONObject(i);
String className = item.getString("class-name");
try {
Class<?> clazzy = Class.forName(className);
T newItem = (T) clazzy.newInstance();
newItem.load(obj);
items.add(newItem);
} catch (InstantiationException e) {
// whatever
} catch (IllegalAccessException e) {
// whatever
} catch (ClassNotFoundException e) {
// whatever
}
}
I don't know why but i just renamed my source file COLARR.C to colarr.c and the error vanished! probably you need this
sudo apt-get install g++
In Linux, I normally use this command to recursively grep for a particular text within a dir
grep -rni "string" *
where,
r = recursive i.e, search subdirectories within the current directory
n = to print the line numbers to stdout
i = case insensitive search
Normally this error means that a connection was established with a server but that connection was closed by the remote server. This could be due to a slow server, a problem with the remote server, a network problem, or (maybe) some kind of security error with data being sent to the remote server but I find that unlikely.
Normally a network error will resolve itself given a bit of time, but it sounds like you’ve already given it a bit of time.
cURL sometimes having issue with SSL and SSL certificates. I think that your Apache and/or PHP was compiled with a recent version of the cURL and cURL SSL libraries plus I don't think that OpenSSL was installed in your web server.
Although I can not be certain However, I believe cURL has historically been flakey with SSL certificates, whereas, Open SSL does not.
Anyways, try installing Open SSL on the server and try again and that should help you get rid of this error.
Using Kotlin
Toast.makeText(view!!.context , "your_text", Toast.LENGTH_SHORT).show()
You can put below property in listview tag
android:divider="@null"
(or)
programmatically listview.Divider(null);
here listview
is ListView
reference.
In Python 3, use
print('h', end='')
to suppress the endline terminator, and
print('a', 'b', 'c', sep='')
to suppress the whitespace separator between items. See the documentation for print
Step 1. Prepare Elements :
var element = document.getElementById('ElementToAppendAfter');
var newElement = document.createElement('div');
var elementParent = element.parentNode;
Step 2. Append after :
elementParent.insertBefore(newElement, element.nextSibling);
Starting Mongo 4.2
, db.collection.update()
can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field:
// { firstName: "Hello", lastName: "World" }
db.collection.update(
{},
[{ $set: { name: { $concat: [ "$firstName", " ", "$lastName" ] } } }],
{ multi: true }
)
// { "firstName" : "Hello", "lastName" : "World", "name" : "Hello World" }
The first part {}
is the match query, filtering which documents to update (in our case all documents).
The second part [{ $set: { name: { ... } }]
is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set
is a new aggregation operator and an alias of $addFields
.
Don't forget { multi: true }
, otherwise only the first matching document will be updated.
Always use nvarchar.
You may never need the double-byte characters for most applications. However, if you need to support double-byte languages and you only have single-byte support in your database schema it's really expensive to go back and modify throughout your application.
The cost of migrating one application from varchar to nvarchar will be much more than the little bit of extra disk space you'll use in most applications.
/* Select some int which does not exist */
int x = ((int)(SQL_Cmd.ExecuteScalar() ?? 0));
in case someone got stuck with this and none of the answers above worked, below is what worked for me. Hope it helps.
var oldString = "\\r|\\n";
// None of these worked for me
// var newString = oldString(@"\\", @"\");
// var newString = oldString.Replace("\\\\", "\\");
// var newString = oldString.Replace("\\u5b89", "\u5b89");
// var newString = Regex.Replace(oldString , @"\\", @"\");
// This is what worked
var newString = Regex.Unescape(oldString);
// newString is now "\r|\n"
The final keyword is used to declare constants.
final int FILE_TYPE = 3;
The finally keyword is used in a try catch statement to specify a block of code to execute regardless of thrown exceptions.
try
{
//stuff
}
catch(Exception e)
{
//do stuff
}
finally
{
//this is always run
}
And finally (haha), finalize im not entirely sure is a keyword, but there is a finalize() function in the Object class.
<textarea name='Status'> </textarea>
<input type='button' value='Status Update'>
You have few problems with your code like using .
for concatenation
Try this -
$(function () {
$('input').on('click', function () {
var Status = $(this).val();
$.ajax({
url: 'Ajax/StatusUpdate.php',
data: {
text: $("textarea[name=Status]").val(),
Status: Status
},
dataType : 'json'
});
});
});
The below steps worked for me for the same issue:
Scenario:
I was trying to add 2 new fields to my existing model for Email functionality. The new fields are "IsEmailVerified" and "ActivationCode"
Steps i have followed:
1.Deleted old migration files under "Migrations" folder which are prevented me to do Update-Database 2.Reverted all my recent changes that i have did on the model
3.Run the below command:
Add-Migration -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=DESKTOP\SQLEXPRESS;Initial Catalog=Custom;Persist Security Info=True;User ID=sa;password=****"
4.Deleted the contents from Up() and Down() methods from migration file and left the methods empty
5.Run the below command:
Update-Database -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=DESKTOP\SQLEXPRESS;Initial Catalog=Custom;Persist Security Info=True;User ID=sa;password="***
After executes the above step, model and DB looks sync.
Now, i added the new properties in the model
public bool IsEmailVerified { get; set; }
public Guid ActivationCode { get; set; }
Run the below command:
Add-Migration -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=DESKTOP\SQLEXPRESS;Initial Catalog=Custom;Persist Security Info=True;User ID=sa;password="***
Now the migration file contains only my recent changes as below:
public override void Up()
{
AddColumn("dbo.UserAccounts", "IsEmailVerified", c => c.Boolean(nullable: false));
AddColumn("dbo.UserAccounts", "ActivationCode", c => c.Guid(nullable: false));
}
public override void Down()
{
DropColumn("dbo.UserAccounts", "ActivationCode");
DropColumn("dbo.UserAccounts", "IsEmailVerified");
}
Run the below command: Update-Database -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=DESKTOP\SQLEXPRESS;Initial Catalog=Custom;Persist Security Info=True;User ID=sa;password="***
11.Now i successfully updated the database with additional columns.
The below is updated table after the recent changes:
On Unity3d, int.Parse
doesn't work well. So I use like bellow.
List<int> intList = new List<int>( Array.ConvertAll(sNumbers.Split(','),
new Converter<string, int>((s)=>{return Convert.ToInt32(s);}) ) );
Hope this help for Unity3d Users.
Include the jQuery file first:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
</script>
For those of you struggling with getting this done trying every possible answer you can find on SO. Here's what worked for me on a VPS running Windows 2012 R2 :
Place your sql file wherever the bin is for me it is located at C:\Program Files\MySQL\MySQL Server 8.0\bin
Open windows command prompt (cmd)
C:\Program Files\MySQL\MySQL Server 8.0\bin > mysql -u [username] -p
use [database_name]
;C://Program Files//MySQL//MySQL Server 8.0//bin//mydatabasename.sql
It did it for me as everything else had failed. It might help you too.
Wrap the child you want centered in a View and make the View absolute.
<View style={{position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'center', alignItems: 'center'}}>
<Text>Centered text</Text>
</View>
You should configure offHeap memory settings as shown below:
val spark = SparkSession
.builder()
.master("local[*]")
.config("spark.executor.memory", "70g")
.config("spark.driver.memory", "50g")
.config("spark.memory.offHeap.enabled",true)
.config("spark.memory.offHeap.size","16g")
.appName("sampleCodeForReference")
.getOrCreate()
Give the driver memory and executor memory as per your machines RAM availability. You can increase the offHeap size if you are still facing the OutofMemory issue.
This is quite late, but interestingly never mentioned yet.
select stuff(x,len(x),1,'')
ie:
take a string x
go to its last character
remove one character
add nothing
Looks like the answers above are for when you are writing and compiling a program, but I'm using a Vendor's software, Catalog.exe
, part of the Voyager
card catalog by "Ex Libris" and I'm getting the error as well:
catalog-error.png http://img805.imageshack.us/img805/8275/catalogerror.png
I have two Windows 7 32-bit machines. The newer one is giving me the error but on the older one it runs fine. I have done a lot of research with Google and here are some of the things I've found that people are saying related to this issue. Maybe one of these things will help fix the error for you, although they didn't work for me:
Run-Time Error 380
(try updating)sfc /scannow
Run as Administrator
)From what others are saying (like David M) I think it could be related to the MSVBM60.DLL
library - but it appears that on both of my computers this file is the exact same (same version, size, date, etc).
Since that file wasn't different I tried to find what other (dll) files the application could be using, so I launched Process Explorer by Sysinternals and took a look at the application (it loads and then crashes when you tell it to "connect"), and the screenshots below are what I found.
screen1.png http://img195.imageshack.us/img195/2231/screen1oo.png
screen2.png http://img88.imageshack.us/img88/2153/screen2ao.png
Now, I'm not a Windows / VB programmer, just a power user, and so I'm about at the end of my knowledge for what to do. I've talked to the software vendor and they recommend reinstalling Windows. That will probably work, but it just bugs me that this program can run on Windows 7, but something on this particular system is causing errors. Finally, this is an image that has been deployed on multiple machines already and so while re-installing Windows once is not a big deal it would save me some serious time if I could figure out a fix or workaround.
In MATLAB R2015a or newer, it is no longer necessary (or advisable from a performance standpoint) to use fspecial
followed by imfilter
since there is a new function called imgaussfilt
that performs this operation in one step and more efficiently.
The basic syntax:
B = imgaussfilt(A,sigma)
filters imageA
with a 2-D Gaussian smoothing kernel with standard deviation specified bysigma
.
The size of the filter for a given Gaussian standard deviation (sigam
) is chosen automatically, but can also be specified manually:
B = imgaussfilt(A,sigma,'FilterSize',[3 3]);
The default is 2*ceil(2*sigma)+1
.
Additional features of imgaussfilter
are ability to operate on gpuArray
s, filtering in frequency or spacial domain, and advanced image padding options. It looks a lot like IPP... hmmm. Plus, there's a 3D version called imgaussfilt3
.
Another simple way:
Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')
Placing @Transient
on getter with private field worked for me.
private String name;
@Transient
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
In addition to Lion's answer i can say that you better use if(CollectionUtils.isNotEmpty(test)){...}
This also checks for null, so no manual check is not needed.
Say your model is 'Shop'
class Shop(models.Model):
street = models.CharField(max_length=150)
city = models.CharField(max_length=150)
# some of your models may have explicit ordering
class Meta:
ordering = ('city')
Since you may have the Meta
class ordering
attribute set, you can use order_by()
without parameters to clear any ordering when using distinct()
. See the documentation under order_by
()
If you don’t want any ordering to be applied to a query, not even the default ordering, call order_by() with no parameters.
and distinct()
in the note where it discusses issues with using distinct()
with ordering.
To query your DB, you just have to call:
models.Shop.objects.order_by().values('city').distinct()
It returns a dictionnary
or
models.Shop.objects.order_by().values_list('city').distinct()
This one returns a ValuesListQuerySet
which you can cast to a list
.
You can also add flat=True
to values_list
to flatten the results.
See also: Get distinct values of Queryset by field
As was said you need to remove the FKs before. On Mysql do it like this:
ALTER TABLE `table_name` DROP FOREIGN KEY `id_name_fk`;
ALTER TABLE `table_name` DROP INDEX `id_name_fk`;
The usual way is to assign some JavaScript to the onClick
attribute of the TR
element.
If you can't use JavaScript, then you must use a trick:
Add the same link to each TD
of the same row (the link must be the outermost element in the cell).
Turn links into block elements: a { display: block; width: 100%; height: 100%; }
The latter will force the link to fill the whole cell so clicking anywhere will invoke the link.
I'd rather implement TaskExecuteAsync interface function for IHttpActionResult. Something like:
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
switch ((Int32)_respContent.Code)
{
case 1:
case 6:
case 7:
response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
break;
case 2:
case 3:
case 4:
response = _request.CreateResponse(HttpStatusCode.BadRequest, _respContent);
break;
}
return Task.FromResult(response);
}
, where _request is the HttpRequest and _respContent is the payload.
Checking the above suggestions on Windows 10 LTSB, and with a glimpse on the "help" outlines (that can be viewed when typing 'command /?' on the cmd), brought me to the conclusion that the PATH command changes the system environment variable Path values only for the current session, but after reboot all the values reset to their default- just as they were prior to using the PATH command.
On the other hand using the SETX command with administrative privileges is way more powerful. It changes those values for good (or at least until the next time this command is used or until next time those values are manually GUI manipulated... ).
The best SETX syntax usage that worked for me:
SETX PATH "%PATH%;C:\path\to\where\the\command\resides"
where any equal sign '=' should be avoided, and don't you worry about spaces! There isn't any need to insert any more quotation marks for a path that contains spaces inside it - the split sign ';' does the job.
The PATH keyword that follows the SETX defines which set of values should be changed among the System Environment Variables possible values, and the %PATH% (the word PATH surrounded by the percent sign) inside the quotation marks, tells the OS to leave the existing PATH values as they are and add the following path (the one that follows the split sign ';') to the existing values.
If you set the border-collapse
style to collapse
on the parent table you should be able to style the tr
:
(styles are inline for demo)
<table style="border-collapse: collapse;">
<tr>
<td>No Border</td>
</tr>
<tr style="border:2px solid #f00;">
<td>Border</td>
</tr>
<tr>
<td>No Border</td>
</tr>
</table>
Output:
You can use this snippet:
static void Main(string[] args)
{
Console.WriteLine("Enter number:");
int fnum = 0;
bool chek = Int32.TryParse(Console.ReadLine(),out fnum);
Console.WriteLine("Enter number:");
int snum = 0;
chek = Int32.TryParse(Console.ReadLine(),out snum);
Console.WriteLine("Enter number:");
int thnum = 0;
chek = Int32.TryParse(Console.ReadLine(),out thnum);
int[] arr = AddToArr(fnum,snum,thnum);
IOrderedEnumerable<int> oarr = arr.OrderBy(delegate(int s)
{
return s;
});
Console.WriteLine("Here your result:");
oarr.ToList().FindAll(delegate(int num) {
Console.WriteLine(num);
return num > 0;
});
}
public static int[] AddToArr(params int[] arr) {
return arr;
}
I hope this will help to you, just change the type
The ng-options
directive does not set the value attribute on the <options>
elements for arrays:
Using limit.value as limit.text for limit in limits
means:
set the
<option>
's label aslimit.text
save thelimit.value
value into the select'sng-model
See Stack Overflow question AngularJS ng-options not rendering values.
Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first
and second
members in your code:
std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };
for (const auto &[k, v] : myMap)
std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;
Output:
m[x] = (a, b)
m[y] = (c, d)
There are several ways to convert SVG to PNG using the Canvg library.
In my case, I needed to get the PNG blob from inline SVG.
The library documentation provides an example (see OffscreenCanvas example).
But this method does not work at the moment in Firefox. Yes, you can enable the gfx.offscreencanvas.enabled option in the settings. But will every user on the site do this? :)
However, there is another way that will work in Firefox too.
const el = document.getElementById("some-svg"); //this is our inline SVG
var canvas = document.createElement('canvas'); //create a canvas for the SVG render
canvas.width = el.clientWidth; //set canvas sizes
canvas.height = el.clientHeight;
const svg = new XMLSerializer().serializeToString(el); //convert SVG to string
//render SVG inside canvas
const ctx = canvas.getContext('2d');
const v = await Canvg.fromString(ctx, svg);
await v.render();
let canvasBlob = await new Promise(resolve => canvas.toBlob(resolve));
For the last line thanks to this answer
As an alternative to the chosen answer, and with the same safe semantics of Marcel's, here is a compact way of using a Python dictionary to specify the values. It has the benefit of being easy to modify as you add or remove columns to insert:
meta_cols=('SongName','SongArtist','SongAlbum','SongGenre')
insert='insert into Songs ({0}) values ({1})'.
.format(','.join(meta_cols), ','.join( ['%s']*len(meta_cols) ))
args = [ meta[i] for i in meta_cols ]
cursor=db.cursor()
cursor.execute(insert,args)
db.commit()
Where meta is the dictionary holding the values to insert. Update can be done in the same way:
meta_cols=('SongName','SongArtist','SongAlbum','SongGenre')
update='update Songs set {0} where id=%s'.
.format(','.join([ '{0}=%s'.format(c) for c in meta_cols ]))
args = [ meta[i] for i in meta_cols ]
args.append( songid )
cursor=db.cursor()
cursor.execute(update,args)
db.commit()
another solution is the function you can embed into your own utils.py
import time as time_ #make sure we don't override time
def millis():
return int(round(time_.time() * 1000))
How to disable submit button
just call a function on onclick event and... return true to submit and false to disable submit. OR call a function on window.onload like :
window.onload = init();
and in init() do something like this :
var theForm = document.getElementById(‘theForm’);
theForm.onsubmit = // what ever you want to do
This answer will be robust enough to work for elements that aren't on the page, therefore failing gracefully (not throwing an exception) if the selector failed to find the element.
const nameSelector = '[data-automation="name-input"]';
const nameInputIsDisplayed = () => {
return $$(nameSelector).count()
.then(count => count !== 0)
}
it('should be displayed', () => {
nameInputIsDisplayed().then(isDisplayed => {
expect(isDisplayed).toBeTruthy()
})
})
You can use anonymous types for example:
var empData = from res in _db.EMPLOYEEs
where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
select new { res.EMAIL, res.USER_NAME };
sep='\t'
is often used for Tab-delimited file.
instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0;
once your window has scrolled pass a certain height:
jQuery
$(window).scroll(function(){
if ($(this).scrollTop() > 135) {
$('#task_flyout').addClass('fixed');
} else {
$('#task_flyout').removeClass('fixed');
}
});
css
.fixed {position:fixed; top:0; left:0;}
As 'localStorage' is just another object, you can: create, view, and edit it in the 'Console'. Simply enter 'localStorage' as a command and press enter, it'll display a string containing the key-value pairs of localStorage (Tip: Click on that string for formatted output, i.e. to display each key-value pair in each line).
Replying in particular to:
You can create a new interface in the networking panel, based on an existing interface, but it will not act as a real fully functional interface (if the original interface is inactive, then the derived one is also inactive).
This can be achieved using a Tun/Tap device as suggested by psv141, and manipulating the /Library/Preferences/SystemConfiguration/preferences.plist
file to add a NetworkService based on either a tun or tap interface. Mac OS X will not allow the creation of a NetworkService based on a virtual network interface, but one can directly manipulate the preferences.plist
file to add the NetworkService by hand. Basically you would open the preferences.plist
file in Xcode (or edit the XML directly, but Xcode is likely to be more fool-proof), and copy the configuration from an existing Ethernet interface. The place to create the new NetworkService is under "NetworkServices", and if your Mac has an Ethernet device the NetworkService profile will also be under this property entry. The Ethernet entry can be copied pretty much verbatim, the only fields you would actually be changing are:
Then you would also manipulate the particular Location you want this NetworkService for (remember Mac OS X can configure all network interfaces dependent on your "Location"). The default location UUID can be obtained in the root of the PropertyList as the key "CurrentSet". After figuring out which location (or set) you want, expand the Set property, and add entries under Global/IPv4/ServiceOrder with the UUID of the new NetworkService. Also under the Set property you need to expand the Service property and add the UUID here as a dictionary with one String entry with key __LINK__ and value as the UUID (use the other interfaces as an example).
After you have modified your preferences.plist
file, just reboot, and the NetworkService will be available under SystemPreferences->Network. Note that we have mimicked an Ethernet device so Mac OS X layer of networking will note that "a cable is unplugged" and will not let you activate the interface through the GUI. However, since the underlying device is a tun/tap device and it has an IP address, the interface will become active and the proper routing will be added at the BSD level.
As a reference this is used to do special routing magic.
In case you got this far and are having trouble, you have to create the tun/tap device by opening one of the devices under /dev/. You can use any program to do this, but I'm a fan of good-old-fashioned C myself:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int fd = open("/dev/tun0", O_RDONLY);
if (fd < 0)
{
printf("Failed to open tun/tap device. Are you root? Are the drivers installed?\n");
return -1;
}
while (1)
{
sleep(100000);
}
return 0;
}
If you are looking for an ORM that implements the Data Mapper paradigm rather than Active Record specifically, then I would strongly suggest that you take a look at GacelaPHP.
Gacela features:
Other ORM solutions are too bloated or have burdensome limitations when developing anything remotely complicated. Gacela resolves the limitations of the active record approach by implementing the Data Mapper Pattern while keeping bloat to a minimum by using PDO for all interactions with the database and Memcached.
I use Cloud Turtle to get the size of individual buckets. If the bucket size exceeds >100 Gb, then it would take some time to display the size. Cloud turtle is freeware.
You should use reflect.DeepEqual()
DeepEqual is a recursive relaxation of Go's == operator.
DeepEqual reports whether x and y are “deeply equal,” defined as follows. Two values of identical type are deeply equal if one of the following cases applies. Values of distinct types are never deeply equal.
Array values are deeply equal when their corresponding elements are deeply equal.
Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.
Func values are deeply equal if both are nil; otherwise they are not deeply equal.
Interface values are deeply equal if they hold deeply equal concrete values.
Map values are deeply equal if they are the same map object or if they have the same length and their corresponding keys (matched using Go equality) map to deeply equal values.
Pointer values are deeply equal if they are equal using Go's == operator or if they point to deeply equal values.
Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal.
Other values - numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.
If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:
<?php phpinfo(); ?>
. Open this page, and look for sendmail path
. (Then, don't forget to remove this code!)-t -i
, then edit your server's php.ini
and add the following line: sendmail_path = /usr/sbin/sendmail -t -i;
But, after being able to send mail with PHP mail()
function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch from mail()
to PHPMailer
with SMTP, after all.
This is the best option. As said Michal Gasek (first answer), since the pull request was merged (https://github.com/ansible/ansible/pull/8651), we are able to set permanent environment variables easily by play level.
- hosts: all
roles:
- php
- nginx
environment:
MY_ENV_VARIABLE: whatever_value
Coming from a strict OO upbringing I'd go for
callback instanceof Function
Strings are prone to either my awful spelling or other typos. Plus I feel it reads better.
As others have said, the style you're after is actually just the Mac OS checkbox style, so it will look radically different on other devices.
In fact both screenshots you linked show what checkboxes look like on Mac OS in Chrome, the grey one is shown at non-100% zoom levels.
It's not a bug in ARel, it's a bug in your logic.
What you want here is:
Foo.includes(:bar).where(Bar.arel_table[:id].not_eq(nil))
The MSDN is a good reference for these type of questions regarding syntax and usage. This is from the Transact SQL Reference - CASE page.
http://msdn.microsoft.com/en-us/library/ms181765.aspx
USE AdventureWorks2012;
GO
SELECT ProductNumber, Name, "Price Range" =
CASE
WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
WHEN ListPrice < 50 THEN 'Under $50'
WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
ELSE 'Over $1000'
END
FROM Production.Product
ORDER BY ProductNumber ;
GO
Another good site you may want to check out if you're using SQL Server is SQL Server Central. This has a large variety of resources available for whatever area of SQL Server you would like to learn.
When using ->get()
you cannot simply use any of the below:
if (empty($result)) { }
if (!$result) { }
if ($result) { }
Because if you dd($result);
you'll notice an instance of Illuminate\Support\Collection
is always returned, even when there are no results. Essentially what you're checking is $a = new stdClass; if ($a) { ... }
which will always return true.
To determine if there are any results you can do any of the following:
if ($result->first()) { }
if (!$result->isEmpty()) { }
if ($result->count()) { }
if (count($result)) { }
You could also use ->first()
instead of ->get()
on the query builder which will return an instance of the first found model, or null
otherwise. This is useful if you need or are expecting only one result from the database.
$result = Model::where(...)->first();
if ($result) { ... }
Notes / References
->first()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_firstisEmpty()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_isEmpty->count()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_countcount($result)
works because the Collection implements Countable and an internal count()
method: http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_countThe Collection and the Query Builder differences can be a bit confusing to newcomers of Laravel because the method names are often the same between the two. For that reason it can be confusing to know what one you’re working on. The Query Builder essentially builds a query until you call a method where it will execute the query and hit the database (e.g. when you call certain methods like ->all()
->first()
->lists()
and others). Those methods also exist on the Collection
object, which can get returned from the Query Builder if there are multiple results. If you're not sure what class you're actually working with, try doing var_dump(User::all())
and experimenting to see what classes it's actually returning (with help of get_class(...)
). I highly recommend you check out the source code for the Collection class, it's pretty simple. Then check out the Query Builder and see the similarities in function names and find out when it actually hits the database.
As of C++17 there is:
if (std::filesystem::exists(pathname)) {
...
You Can try usimg
backgroundImage: url(process.env.PUBLIC_URL + "/ assets/image_location")
Try "perldoc -l":
$ perldoc -l Log::Dispatch /usr/local/share/perl/5.26.1/Log/Dispatch.pm
Found an easy way which works with all browsers I have (Chrome 49, Edge 25, Firefox 44, IE11, Safari 5 [Win], Safari 8 (MacOS)) :
// Clean svg content (if you want to update the svg's objects)_x000D_
// Note : .html('') doesn't works for svg in some browsers_x000D_
$('#svgObject').empty();_x000D_
// add some objects_x000D_
$('#svgObject').append('<polygon class="svgStyle" points="10,10 50,10 50,50 10,50 10,10" />');_x000D_
$('#svgObject').append('<circle class="svgStyle" cx="100" cy="30" r="25"/>');_x000D_
_x000D_
// Magic happens here: refresh DOM (you must refresh svg's parent for Edge/IE and Safari)_x000D_
$('#svgContainer').html($('#svgContainer').html());
_x000D_
.svgStyle_x000D_
{_x000D_
fill:cornflowerblue;_x000D_
fill-opacity:0.2;_x000D_
stroke-width:2;_x000D_
stroke-dasharray:5,5;_x000D_
stroke:black;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="svgContainer">_x000D_
<svg id="svgObject" height="100" width="200"></svg>_x000D_
</div>_x000D_
_x000D_
<span>It works if two shapes (one square and one circle) are displayed above.</span>
_x000D_
You could save yourself a bunch of space by using jQuery. You only need to use:
$('#myElement').trigger("click")
You can project 3D point in 2D using: Commons Math: The Apache Commons Mathematics Library with just two classes.
Example for Java Swing.
import org.apache.commons.math3.geometry.euclidean.threed.Plane;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
Plane planeX = new Plane(new Vector3D(1, 0, 0));
Plane planeY = new Plane(new Vector3D(0, 1, 0)); // Must be orthogonal plane of planeX
void drawPoint(Graphics2D g2, Vector3D v) {
g2.drawLine(0, 0,
(int) (world.unit * planeX.getOffset(v)),
(int) (world.unit * planeY.getOffset(v)));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawPoint(g2, new Vector3D(2, 1, 0));
drawPoint(g2, new Vector3D(0, 2, 0));
drawPoint(g2, new Vector3D(0, 0, 2));
drawPoint(g2, new Vector3D(1, 1, 1));
}
Now you only needs update the planeX
and planeY
to change the perspective-projection, to get things like this:
Using iReport designer 5.6.0, if you wish to compile multiple jrxml files without previewing - go to Tools -> Massive Processing Tool. Select Elaboration Type as "Compile Files", select the folder where all your jrxml reports are stored, and compile them in a batch.
So here's how to do that:
In the bottom bar of VSCode, you'll see the label
UTF-8
. Click it. A popup opens. ClickSave with encoding
. You can now pick a new encoding for that file.
Alternatively, you can change the setting globally in Workspace/User settings using the setting "files.encoding": "utf8"
. If using the graphical settings page in VSCode, simply search for encoding
. Do note however that this only applies to newly created files.
To complete the current answers and as the question is not language specific, some C-project use the prefix m_
to define global variables that are specific to a file - and g_
for global variables that have a scoped larger than the file they are defined.
In this case global variables defined with prefix m_
should be defined as static
.
See EDK2 (a UEFI Open-Source implementation) coding convention for an example of project using this convention.
You can do it in LibreOffice Draw (which is usually preinstalled in Ubuntu):
However the cmd/batch version works you can run into an issue when you want to define an eventID which is higher then 1000. For event creation with an eventID of 1000+ i'll use powershell like this:
$evt=new-object System.Diagnostics.Eventlog(“Define Logbook”)
$evt.Source=”Define Source”
$evtNumber=Define Eventnumber
$evtDescription=”Define description”
$infoevent=[System.Diagnostics.EventLogEntryType]::Define error level
$evt.WriteEntry($evtDescription,$infoevent,$evtNumber)
Sample:
$evt=new-object System.Diagnostics.Eventlog(“System”)
$evt.Source=”Tcpip”
$evtNumber=4227
$evtDescription=”This is a Test Event”
$infoevent=[System.Diagnostics.EventLogEntryType]::Warning
$evt.WriteEntry($evtDescription,$infoevent,$evtNumber)
You can use Map and Spread Operator:
var rawData = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"];_x000D_
_x000D_
var unique = new Map();_x000D_
rawData.forEach(d => unique.set(d, d));_x000D_
var uniqueItems = [...unique.keys()];_x000D_
_x000D_
console.log(uniqueItems);
_x000D_
This worked for me:
background: #4C2516 url('imagename.png') repeat-y 0 0;
In your 'encrypt' method, you should either get rid of the try/catch and instead add a try/catch around where you call encrypt (inside 'actionPerformed') or return null inside the catch within encrypt (that's the second error.
Just adding to the solutions already suggested. Assumes same height, no resizing.
import sys
import glob
from PIL import Image
Image.MAX_IMAGE_PIXELS = 100000000 # For PIL Image error when handling very large images
imgs = [ Image.open(i) for i in list_im ]
widths, heights = zip(*(i.size for i in imgs))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
# Place first image
new_im.paste(imgs[0],(0,0))
# Iteratively append images in list horizontally
hoffset=0
for i in range(1,len(imgs),1):
**hoffset=imgs[i-1].size[0]+hoffset # update offset**
new_im.paste(imgs[i],**(hoffset,0)**)
new_im.save('output_horizontal_montage.jpg')
Like that we can do....
int main(int argc, char *argv[]) {
int a, b, c;
*// Converting string type to integer type
// using function "atoi( argument)"*
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);
}
Though some of the answers mention it rightly that we can use the Selected State to set an image for Selected state of the button, it won't work elegantly when the button has to have both image and text.
Like many, I ended by subclassing UIButton; however, added support for setting images from Interface Builder.
Below is my code:
import UIKit
class CustomCheckbox: UIButton {
@IBInspectable var defaultStateImage: UIImage? = nil {
didSet{
self.setNeedsDisplay()
}
}
@IBInspectable var selectedStateImage: UIImage? = nil {
didSet{
self.setNeedsDisplay()
}
}
@IBInspectable var gapPadding: CGFloat = 0 {
didSet{
self.setNeedsDisplay()
}
}
@IBInspectable var isChecked: Bool = false {
didSet{
self.setNeedsDisplay()
}
}
var defaultImageView: UIImageView? = nil
var selectedImageView: UIImageView? = nil
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override func layoutSubviews() {
super.layoutSubviews()
setup()
}
func setup() {
if(defaultStateImage != nil) {
defaultImageView = UIImageView(image: defaultStateImage)
defaultImageView?.translatesAutoresizingMaskIntoConstraints = false
addSubview(defaultImageView!)
let length = CGFloat(16)
titleEdgeInsets.left += length
NSLayoutConstraint.activate([
defaultImageView!.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: -gapPadding),
defaultImageView!.centerYAnchor.constraint(equalTo: self.titleLabel!.centerYAnchor, constant: 0),
defaultImageView!.widthAnchor.constraint(equalToConstant: length),
defaultImageView!.heightAnchor.constraint(equalToConstant: length)
])
}
if(selectedStateImage != nil) {
selectedImageView = UIImageView(image: selectedStateImage)
selectedImageView!.translatesAutoresizingMaskIntoConstraints = false
addSubview(selectedImageView!)
let length = CGFloat(16)
titleEdgeInsets.left += length
NSLayoutConstraint.activate([
selectedImageView!.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: -gapPadding),
selectedImageView!.centerYAnchor.constraint(equalTo: self.titleLabel!.centerYAnchor, constant: 0),
selectedImageView!.widthAnchor.constraint(equalToConstant: length),
selectedImageView!.heightAnchor.constraint(equalToConstant: length)
])
}
if defaultImageView != nil {
defaultImageView!.isHidden = isChecked
}
if selectedImageView != nil {
selectedImageView!.isHidden = !isChecked
}
self.addTarget(self, action: #selector(checkChanged(_:)), for: .touchUpInside)
}
@objc func checkChanged(_ btn : UIButton){
self.isChecked = !self.isChecked
if defaultImageView != nil {
defaultImageView!.isHidden = isChecked
}
if selectedImageView != nil {
selectedImageView!.isHidden = !isChecked
}
}
}
All you need is:
[OutputCache(Duration=0)]
public JsonResult MyAction(
or, if you want to disable it for an entire Controller:
[OutputCache(Duration=0)]
public class MyController
Despite the debate in comments here, this is enough to disable browser caching - this causes ASP.Net to emit response headers that tell the browser the document expires immediately:
Try the following command.
:set binary
In VIM, this should do the same thing as using the "-b" command line option. If you put this in your startup (i.e. .vimrc) file, it will always be in place for you.
On many *nix systems, there is a "dos2unix" or "unix2dos" command that can process the file and correct any suspected line ending issues. If there is no problem with the line endings, the files will not be changed.
I know it's to late to answer this question. But if you are working with collection of type IList<> and you don't care about an order of the returned collection, then this method is working faster. I've used Mark Byers answer and made a little changes. So now method TakeLast is:
public static IEnumerable<T> TakeLast<T>(IList<T> source, int takeCount)
{
if (source == null) { throw new ArgumentNullException("source"); }
if (takeCount < 0) { throw new ArgumentOutOfRangeException("takeCount", "must not be negative"); }
if (takeCount == 0) { yield break; }
if (source.Count > takeCount)
{
for (int z = source.Count - 1; takeCount > 0; z--)
{
takeCount--;
yield return source[z];
}
}
else
{
for(int i = 0; i < source.Count; i++)
{
yield return source[i];
}
}
}
For test I have used Mark Byers method and kbrimington's andswer. This is test:
IList<int> test = new List<int>();
for(int i = 0; i<1000000; i++)
{
test.Add(i);
}
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
IList<int> result = TakeLast(test, 10).ToList();
stopwatch.Stop();
Stopwatch stopwatch1 = new Stopwatch();
stopwatch1.Start();
IList<int> result1 = TakeLast2(test, 10).ToList();
stopwatch1.Stop();
Stopwatch stopwatch2 = new Stopwatch();
stopwatch2.Start();
IList<int> result2 = test.Skip(Math.Max(0, test.Count - 10)).Take(10).ToList();
stopwatch2.Stop();
And here are results for taking 10 elements:
and for taking 1000001 elements results are:
Works in Ubuntu 20.04
Add this line inside <policymap>
<policy domain="module" rights="read|write" pattern="{PS,PDF,XPS}" />
Comment these lines:
<!--
<policy domain="coder" rights="none" pattern="PS" />
<policy domain="coder" rights="none" pattern="PS2" />
<policy domain="coder" rights="none" pattern="PS3" />
<policy domain="coder" rights="none" pattern="EPS" />
<policy domain="coder" rights="none" pattern="PDF" />
<policy domain="coder" rights="none" pattern="XPS" />
-->
To put the same text in a certain number of cells do the following:
You will find that all the highlighted cells now have the same data in them. Have a nice day.
This one seems to be a better fit:
<#if userName?has_content>
... do something
</#if>
http://freemarker.sourceforge.net/docs/ref_builtins_expert.html
in laravel used decimal column type for migration
$table->decimal('latitude', 10, 8);
$table->decimal('longitude', 11, 8);
for more information see available column type
In addition to Benjamin's answer - in case if you are using Spring Security, placing the CharacterEncodingFilter in web.xml might not always work. In this case you need to create a custom filter and add it to the filter chain as the first filter. To make sure it's the first filter in the chain, you need to add it before ChannelProcessingFilter, using addFilterBefore
in your WebSecurityConfigurerAdapter:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//add your custom encoding filter as the first filter in the chain
http.addFilterBefore(new EncodingFilter(), ChannelProcessingFilter.class);
http.authorizeRequests()
.and()
// your code here ...
}
}
The ordering of all filters in Spring Security is available here: HttpSecurityBuilder - addFilter()
Your custom UTF-8 encoding filter can look like following:
public class EncodingFilter extends GenericFilterBean {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
}
Don't forget to add in your jsp files:
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
And remove the CharacterEncodingFilter from web.xml if it's there.
Perhaps you're trying to modularize your package. I'm assuming that package1
and package2
are, in a way, part of the same package but for readability you're splitting those into multiple files.
If the previous case was yours, you could use the same package name into those multiples files and it will be like if there were the same file.
This is an example:
add.go
package math
func add(n1, n2 int) int {
return n1 + n2
}
subtract.go
package math
func subtract(n1, n2 int) int {
return n1 - n2
}
donothing.go
package math
func donothing(n1, n2 int) int {
s := add(n1, n2)
s = subtract(n1, n2)
return s
}
I am not a Go expert and this is my first post in StackOveflow, so if you have some advice it will be well received.
Remove if
from if @item.rigged ? "Yes" : "No"
Ternary operator has form condition ? if_true : if_false
This should work, I tried it by myself and it worked for me. If you pass True instead of false, the print dialog will appear.
this.print(false);
I believe you need to put the libeay32.dll and ssleay32.dll files in the systems folder
I tried to use script for alert()
boxes styles using java-script
.Here i used those JS and CSS.
Refer this coding JS functionality.
var ALERT_TITLE = "Oops!";
var ALERT_BUTTON_TEXT = "Ok";
if(document.getElementById) {
window.alert = function(txt) {
createCustomAlert(txt);
}
}
function createCustomAlert(txt) {
d = document;
if(d.getElementById("modalContainer")) return;
mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
mObj.id = "modalContainer";
mObj.style.height = d.documentElement.scrollHeight + "px";
alertObj = mObj.appendChild(d.createElement("div"));
alertObj.id = "alertBox";
if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
alertObj.style.visiblity="visible";
h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode(ALERT_TITLE));
msg = alertObj.appendChild(d.createElement("p"));
//msg.appendChild(d.createTextNode(txt));
msg.innerHTML = txt;
btn = alertObj.appendChild(d.createElement("a"));
btn.id = "closeBtn";
btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
btn.href = "#";
btn.focus();
btn.onclick = function() { removeCustomAlert();return false; }
alertObj.style.display = "block";
}
function removeCustomAlert() {
document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}
And CSS for alert()
Box
#modalContainer {
background-color:rgba(0, 0, 0, 0.3);
position:absolute;
width:100%;
height:100%;
top:0px;
left:0px;
z-index:10000;
background-image:url(tp.png); /* required by MSIE to prevent actions on lower z-index elements */
}
#alertBox {
position:relative;
width:300px;
min-height:100px;
margin-top:50px;
border:1px solid #666;
background-color:#fff;
background-repeat:no-repeat;
background-position:20px 30px;
}
#modalContainer > #alertBox {
position:fixed;
}
#alertBox h1 {
margin:0;
font:bold 0.9em verdana,arial;
background-color:#3073BB;
color:#FFF;
border-bottom:1px solid #000;
padding:2px 0 2px 5px;
}
#alertBox p {
font:0.7em verdana,arial;
height:50px;
padding-left:5px;
margin-left:55px;
}
#alertBox #closeBtn {
display:block;
position:relative;
margin:5px auto;
padding:7px;
border:0 none;
width:70px;
font:0.7em verdana,arial;
text-transform:uppercase;
text-align:center;
color:#FFF;
background-color:#357EBD;
border-radius: 3px;
text-decoration:none;
}
/* unrelated styles */
#mContainer {
position:relative;
width:600px;
margin:auto;
padding:5px;
border-top:2px solid #000;
border-bottom:2px solid #000;
font:0.7em verdana,arial;
}
h1,h2 {
margin:0;
padding:4px;
font:bold 1.5em verdana;
border-bottom:1px solid #000;
}
code {
font-size:1.2em;
color:#069;
}
#credits {
position:relative;
margin:25px auto 0px auto;
width:350px;
font:0.7em verdana;
border-top:1px solid #000;
border-bottom:1px solid #000;
height:90px;
padding-top:4px;
}
#credits img {
float:left;
margin:5px 10px 5px 0px;
border:1px solid #000000;
width:80px;
height:79px;
}
.important {
background-color:#F5FCC8;
padding:2px;
}
code span {
color:green;
}
And HTML file:
<input type="button" value = "Test the alert" onclick="alert('Alert this pages');" />
And also View this DEMO: JSFIDDLE and DEMO RESULT IMAGE
If you plan to create a PHP package you most likely want to put in on Packagist to make it available for other with composer.
Composer has the as naming-convention to use vendorname/package-name-is-lowercase-with-hyphens
.
If you plan to create a JS package you probably want to use npm. One of their naming conventions is to not permit upper case letters in the middle of your package name.
Therefore, I would recommend for PHP and JS packages to use lowercase-with-hyphens
and name your packages in composer or npm identically to your package on GitHub.
This is, I believe, a general solution, though I tested it using IBM Informix Dynamic Server 11.50.FC3. The following query:
SELECT grade,
ROUND(100.0 * grade_sum / (SELECT COUNT(*) FROM grades), 2) AS pct_of_grades
FROM (SELECT grade, COUNT(*) AS grade_sum
FROM grades
GROUP BY grade
)
ORDER BY grade;
gives the following output on the test data shown below the horizontal rule. The ROUND
function may be DBMS-specific, but the rest (probably) is not. (Note that I changed 100 to 100.0 to ensure that the calculation occurs using non-integer - DECIMAL, NUMERIC - arithmetic; see the comments, and thanks to Thunder.)
grade pct_of_grades
CHAR(1) DECIMAL(32,2)
A 32.26
B 16.13
C 12.90
D 12.90
E 9.68
F 16.13
CREATE TABLE grades
(
id VARCHAR(10) NOT NULL,
grade CHAR(1) NOT NULL CHECK (grade MATCHES '[ABCDEF]')
);
INSERT INTO grades VALUES('1001', 'A');
INSERT INTO grades VALUES('1002', 'B');
INSERT INTO grades VALUES('1003', 'F');
INSERT INTO grades VALUES('1004', 'C');
INSERT INTO grades VALUES('1005', 'D');
INSERT INTO grades VALUES('1006', 'A');
INSERT INTO grades VALUES('1007', 'F');
INSERT INTO grades VALUES('1008', 'C');
INSERT INTO grades VALUES('1009', 'A');
INSERT INTO grades VALUES('1010', 'E');
INSERT INTO grades VALUES('1001', 'A');
INSERT INTO grades VALUES('1012', 'F');
INSERT INTO grades VALUES('1013', 'D');
INSERT INTO grades VALUES('1014', 'B');
INSERT INTO grades VALUES('1015', 'E');
INSERT INTO grades VALUES('1016', 'A');
INSERT INTO grades VALUES('1017', 'F');
INSERT INTO grades VALUES('1018', 'B');
INSERT INTO grades VALUES('1019', 'C');
INSERT INTO grades VALUES('1020', 'A');
INSERT INTO grades VALUES('1021', 'A');
INSERT INTO grades VALUES('1022', 'E');
INSERT INTO grades VALUES('1023', 'D');
INSERT INTO grades VALUES('1024', 'B');
INSERT INTO grades VALUES('1025', 'A');
INSERT INTO grades VALUES('1026', 'A');
INSERT INTO grades VALUES('1027', 'D');
INSERT INTO grades VALUES('1028', 'B');
INSERT INTO grades VALUES('1029', 'A');
INSERT INTO grades VALUES('1030', 'C');
INSERT INTO grades VALUES('1031', 'F');
You can use order() to sort date data.
# Sort date ascending order
d[order(as.Date(d$V3, format = "%d/%m/%Y")),]
# Sort date descending order
d[rev(order(as.Date(d$V3, format = "%d/%m/%y"))),]
Hope this helps,
Link to my quora answer https://qr.ae/TWngCe
Thanks
IF PORT 80 IS NOT THE ISSUE!
Check to see if the port 80 is in use first as this can be an issue. You can do this by typing "netstat -an" into cmd. The look for 0.0.0.0:80 under Local Address, if you find this is in use then follow the solution from @Karthik. However, I had a similar issue but my port 80 was not in use. My XAMPP had wrong paths locations, steps to fix this:
1.Find out the Apache version you are using, you can find this by looking in Services (Control panel, Admin Tools, Services) and finding Apache in my case it was listed as Apache2.4
2.Close XAMPP.
3.Run cmd as admin.
4.execute 'sc delete "Apache2.4"' (put your version in place of mine and without the surrounding ' ', but with the " " around Apache).
5.execute 'sc delete "mySQL"', again remove the '' when you type it.
6.reopen XAMPP and try starting Apache
If you are having trouble with FileZill, Mercury, or Tomcat you could try it here too, but I have not tested that myself.
Hope this helps!
LINQ to SQL only supports 1 to 1 mapping of database tables, views, sprocs and functions available in Microsoft SQL Server. It's a great API to use for quick data access construction to relatively well designed SQL Server databases. LINQ2SQL was first released with C# 3.0 and .Net Framework 3.5.
LINQ to Entities (ADO.Net Entity Framework) is an ORM (Object Relational Mapper) API which allows for a broad definition of object domain models and their relationships to many different ADO.Net data providers. As such, you can mix and match a number of different database vendors, application servers or protocols to design an aggregated mash-up of objects which are constructed from a variety of tables, sources, services, etc. ADO.Net Framework was released with the .Net Framework 3.5 SP1.
This is a good introductory article on MSDN: Introducing LINQ to Relational Data
awk '{awk code}' file | tee file
the tee
command take place and executed after the awk
command is finished due to the |
.
For those who have Stata (even though the asker does not) you can use this:
outsheet produces a tab-delimited file so you need to specify the comma
option like below
outsheet [varlist] using file.csv , comma
also, if you want to remove labels (which are included by default
outsheet [varlist] using file.csv, comma nolabel
hat tip to:
If you are worried at all about speed, you should instead use:
mag = np.sqrt(x.dot(x))
Here are some benchmarks:
>>> import timeit
>>> timeit.timeit('np.linalg.norm(x)', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0450878
>>> timeit.timeit('np.sqrt(x.dot(x))', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0181372
EDIT: The real speed improvement comes when you have to take the norm of many vectors. Using pure numpy functions doesn't require any for loops. For example:
In [1]: import numpy as np
In [2]: a = np.arange(1200.0).reshape((-1,3))
In [3]: %timeit [np.linalg.norm(x) for x in a]
100 loops, best of 3: 4.23 ms per loop
In [4]: %timeit np.sqrt((a*a).sum(axis=1))
100000 loops, best of 3: 18.9 us per loop
In [5]: np.allclose([np.linalg.norm(x) for x in a],np.sqrt((a*a).sum(axis=1)))
Out[5]: True
You had several issues with your code.
1) Missing a closing brace, }
, within your rules
.
2) In this case, there is no reason to use a function for the required
rule. By default, the plugin can handle checkbox
and radio
inputs just fine, so using true
is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.
3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength
rule.
4) The messages
option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.
5) If a name
attribute contains brackets, you must enclose it within quotes.
DEMO: http://jsfiddle.net/K6Wvk/
$(document).ready(function () {
$('#formid').validate({ // initialize the plugin
rules: {
'test[]': {
required: true,
maxlength: 2
}
},
messages: {
'test[]': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
}
});
});
I found some more information from this blog.
Had a similar need. $compile
does the job. (Not completely sure if this is "THE" way to do it, still working my way through angular)
http://jsbin.com/ebuhuv/7/edit - my exploration test.
One thing to note (per my example), one of my requirements was that the template would change based on a type
attribute once you clicked save, and the templates were very different. So though, you get the data binding, if need a new template in there, you will have to recompile.
I know the topic is old, but I just fell on it after a google search so... here is another solution:
$array_merged = array_merge($array_going_first, $array_going_second);
This one seems pretty clean to me, it works just fine!
1) do
svn revert . --recursive
2) parse output for errors like
"Failed to revert 'dir1/dir2' -- try updating instead."
3) call svn up for each of error directories:
svn up dir1/dir2
For OSX users:
If you use ls *.{mp3,exe,mp4}
, it will throw an error if one of those extensions has no results.
Using ls *.(mp3|exe|mp4)
will return all files matching those extensions, even if one of the extensions had 0 results.
Two native solutions
performance.now
--> Call to ... took 6.414999981643632
milliseconds.console.time
--> Call to ... took 5.815
millisecondsThe difference between both is precision.
For usage and explanation read on.
Performance.now
(For microsecond precision use)
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
function doSomething(){
for(i=0;i<1000000;i++){var x = i*i;}
}
_x000D_
Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.
Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().
console.time
Example: (timeEnd
wrapped in setTimeout
for simulation)
console.time('Search page');
doSomething();
console.timeEnd('Search page');
function doSomething(){
for(i=0;i<1000000;i++){var x = i*i;}
}
_x000D_
You can change the Timer-Name for different operations.
$_FILES["file"]["name"] - the name of the uploaded file
use
=VLOOKUP(D4,F4:G9,2)
with the range F4:G9:
0 0.1
1 0.15
5 0.2
15 0.3
30 1
100 1.3
and D4
being the value in question, e.g. 18.75
-> result: 0.3
There's actually quite a bit of useful information added to debug allocations. This table is more complete:
http://www.nobugs.org/developer/win32/debug_crt_heap.html#table
Address Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments 0x00320FD8 -40 0x01090009 0x01090009 0x01090009 0x0109005A Win32 heap info 0x00320FDC -36 0x01090009 0x00180700 0x01090009 0x00180400 Win32 heap info 0x00320FE0 -32 0xBAADF00D 0x00320798 0xDDDDDDDD 0x00320448 Ptr to next CRT heap block (allocated earlier in time) 0x00320FE4 -28 0xBAADF00D 0x00000000 0xDDDDDDDD 0x00320448 Ptr to prev CRT heap block (allocated later in time) 0x00320FE8 -24 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Filename of malloc() call 0x00320FEC -20 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Line number of malloc() call 0x00320FF0 -16 0xBAADF00D 0x00000008 0xDDDDDDDD 0xFEEEFEEE Number of bytes to malloc() 0x00320FF4 -12 0xBAADF00D 0x00000001 0xDDDDDDDD 0xFEEEFEEE Type (0=Freed, 1=Normal, 2=CRT use, etc) 0x00320FF8 -8 0xBAADF00D 0x00000031 0xDDDDDDDD 0xFEEEFEEE Request #, increases from 0 0x00320FFC -4 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x00321000 +0 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321004 +4 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321008 +8 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x0032100C +12 0xBAADF00D 0xBAADF00D 0xDDDDDDDD 0xFEEEFEEE Win32 heap allocations are rounded up to 16 bytes 0x00321010 +16 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321014 +20 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321018 +24 0x00000010 0x00000010 0x00000010 0xFEEEFEEE Win32 heap bookkeeping 0x0032101C +28 0x00000000 0x00000000 0x00000000 0xFEEEFEEE Win32 heap bookkeeping 0x00321020 +32 0x00090051 0x00090051 0x00090051 0xFEEEFEEE Win32 heap bookkeeping 0x00321024 +36 0xFEEE0400 0xFEEE0400 0xFEEE0400 0xFEEEFEEE Win32 heap bookkeeping 0x00321028 +40 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping 0x0032102C +44 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping
I have used the following code to compile native dropbox libraries, I am using Android Studio v1.1.
task nativeLibsToJar(type: Zip) {
destinationDir file("$buildDir/native-libs")
baseName 'native-libs'
extension 'jar'
from fileTree(dir: 'src/main/libs', include: '**/*.so')
into 'lib/'
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn(nativeLibsToJar)
}
FileSaver.js should be able to help you here.
var canvas = document.getElementById("my-canvas");
// draw to canvas...
canvas.toBlob(function(blob) {
saveAs(blob, "pretty image.png");
});
I don't know if this was true at the time of the original posting, but the siblings method allows selectors, so a reduction of what the OP listed should work.
$(this).siblings(':not(.closedTab)');
You can learn something called "mocking". You can use this, for example, to check if: - a function was called - a function was called x times - a function was called at least x times - a function was called with a specific set of parameters. In your case, for example, you can use mocking to check that method3 was called once with whatever you pass as arg1 and arg2.
Have a look at these: https://code.google.com/p/mockito/ https://code.google.com/p/powermock/
For convenience, a simple function wrapping the two methods from os.path
:
def filename(path):
"""Return file name without extension from path.
See https://docs.python.org/3/library/os.path.html
"""
import os.path
b = os.path.split(path)[1] # path, *filename*
f = os.path.splitext(b)[0] # *file*, ext
#print(path, b, f)
return f
Tested with Python 3.5.
I solved the problem with the following workaround. Note that I am also scaling the image, which was necessary to avoid OutOfMemoryExceptions.
Beware that this solution will not work properly with portrait images or opside-down images (thank you Timmmm for noting). Timmmm's solution above might be the better choice if that is required and it looks more elegant, too: https://stackoverflow.com/a/8914291/449918
File path = // ... location of your bitmap file
int w = 512; int h = 384; // size that does not lead to OutOfMemoryException on Nexus One
Bitmap b = BitmapFactory.decodeFile(path);
// Hack to determine whether the image is rotated
boolean rotated = b.getWidth() > b.getHeight();
Bitmap resultBmp = null;
// If not rotated, just scale it
if (!rotated) {
resultBmp = Bitmap.createScaledBitmap(b, w, h, true);
b.recycle();
b = null;
// If rotated, scale it by switching width and height and then rotated it
} else {
Bitmap scaledBmp = Bitmap.createScaledBitmap(b, h, w, true);
b.recycle();
b = null;
Matrix mat = new Matrix();
mat.postRotate(90);
resultBmp = Bitmap.createBitmap(scaledBmp, 0, 0, h, w, mat, true);
// Release image resources
scaledBmp.recycle();
scaledBmp = null;
}
// resultBmp now contains the scaled and rotated image
Cheers
For firefox there is also an extension called RESTClient which is quite nice:
Try unbinding the event.
$("span").click(function(){
alert($(this).text());
$("span").not($(this)).unbind('click');
});
Here is the fiddle
document.body.style.cursor = 'cursorurl';
Another base solution
group_sorted <- group[order(group$Subject, -group$pt),]
group_sorted[!duplicated(group_sorted$Subject),]
# Subject pt Event
# 1 5 2
# 2 17 2
# 3 5 2
Order the data frame by pt
(descending) and then remove rows duplicated in Subject
Thanks HansUp for your answer, it is very helpful and it works!
I found three patterns working in Access, yours is the best, because it works in all cases.
INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM
((class
INNER JOIN person AS cr
ON class.C_P_ClassRep=cr.P_Nr
)
INNER JOIN person AS cr2
ON class.C_P_ClassRep2nd=cr2.P_Nr
)
;
INNER JOIN "chained-set pattern"
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM person AS cr
INNER JOIN ( class
INNER JOIN ( person AS cr2
) ON class.C_P_ClassRep2nd=cr2.P_Nr
) ON class.C_P_ClassRep=cr.P_Nr
;
CROSS JOIN with WHERE
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM class, person AS cr, person AS cr2
WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
;
You could create your own class of type Quiz and then deserialize with strong type:
Example:
quizresult = JsonConvert.DeserializeObject<Quiz>(args.Message,
new JsonSerializerSettings
{
Error = delegate(object sender1, ErrorEventArgs args1)
{
errors.Add(args1.ErrorContext.Error.Message);
args1.ErrorContext.Handled = true;
}
});
And you could also apply a schema validation.
You can use django-ipware which supports Python 2 & 3 and handles IPv4 & IPv6.
Install:
pip install django-ipware
Simple Usage:
# In a view or a middleware where the `request` object is available
from ipware import get_client_ip
ip, is_routable = get_client_ip(request)
if ip is None:
# Unable to get the client's IP address
else:
# We got the client's IP address
if is_routable:
# The client's IP address is publicly routable on the Internet
else:
# The client's IP address is private
# Order of precedence is (Public, Private, Loopback, None)
Advanced Usage:
Custom Header - Custom request header for ipware to look at:
i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR'])
i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR', 'REMOTE_ADDR'])
Proxy Count - Django server is behind a fixed number of proxies:
i, r = get_client_ip(request, proxy_count=1)
Trusted Proxies - Django server is behind one or more known & trusted proxies:
i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2'))
# For multiple proxies, simply add them to the list
i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2', '177.3.3.3'))
# For proxies with fixed sub-domain and dynamic IP addresses, use partial pattern
i, r = get_client_ip(request, proxy_trusted_ips=('177.2.', '177.3.'))
Note: read this notice.
A bit more detail to Joachim Sauer's answer:
On Ubuntu at least, the metapackage tomcat6
depends on metapackage tomcat6-common
(and others), which depends on metapackage libtomcat6-java
, which depends on package libservlet2.5-java
(and others). It contains, among others, the files /usr/share/java/servlet-api-2.5.jar
and /usr/share/java/jsp-api-2.1.jar
, which are the servlet and JSP libraries you need. So if you've installed Tomcat 6 through apt-get or the Ubuntu Software Centre, you already have the libraries; all that's left is to get Tomcat to use them in your project.
Place libraries /usr/share/java/servlet-api-2.5.jar
and /usr/share/java/jsp-api-2.1.jar
on the class path like this:
For all projects, by configuring Eclipse by selecting Window -> Preferences -> Java -> Installed JREs, then selecting the JRE you're using, pressing Edit, then pressing Add External JARs, and then by selecting the files from the locations given above.
For just one project, by right-clicking on the project in the Project Explorer pane, then selecting Properties -> Java Build Path, and then pressing Add External JARs, and then by selecting the files from the locations given above.
Further note 1: These are the correct versions of those libraries for use with Tomcat 6; for the other Tomcat versions, see the table on page http://tomcat.apache.org/whichversion.html, though I would suppose each Tomcat version includes the versions of these libraries that are appropriate for it.
Further note 2: Package libservlet2.5-java
's description (dpkg-query -s libservlet2.5-java
) says: 'Apache Tomcat implements the Java Servlet and the JavaServer Pages (JSP) specifications from Sun Microsystems, and provides a "pure Java" HTTP web server environment for Java code to run. This package contains the Java Servlet and JSP library.'
Instead of the option a
use option x
, this will create the directories but only for extraction, not compression.
Update query may have some issues
$query = "UPDATE anstalld SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn' ";
echo $query;
Please make sure that, your variable not having values with qoutes ( ' ), May be the query is breaking somewhere.
echo the query and try to execute in phpmyadmin itself. Then you can find the issues.
This exception happened when I forgot to close the connections
var data = {_x000D_
"items": [{_x000D_
"id": 1,_x000D_
"category": "cat1"_x000D_
}, {_x000D_
"id": 2,_x000D_
"category": "cat2"_x000D_
}, {_x000D_
"id": 3,_x000D_
"category": "cat1"_x000D_
}, {_x000D_
"id": 4,_x000D_
"category": "cat2"_x000D_
}, {_x000D_
"id": 5,_x000D_
"category": "cat1"_x000D_
}]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
The $.grep()
method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.
cmd /k
is the typical way to open any console application (not only Python) with a console window that will remain after the application closes. The easiest way I can think to do that, is to press Win+R, type cmd /k
and then drag&drop the script you want to the Run dialog.
Instead of writing
<hr>
Write
<hr class="col-xs-12">
And it will display full width as normal.
You can use the re.sub() function to remove these characters:
>>> import re
>>> re.sub("[^a-zA-Z]+", "", "ABC12abc345def")
'ABCabcdef'
re.sub(MATCH PATTERN, REPLACE STRING, STRING TO SEARCH)
"[^a-zA-Z]+"
- look for any group of characters that are NOT
a-zA-z.""
- Replace the matched characters with ""I am coming from an Electron environment, where I need IPC communication between a renderer process and the main process. The renderer process sits in an HTML file between script tags and generates the same error.
The line
const {ipcRenderer} = require('electron')
throws the Uncaught ReferenceError: require is not defined
I was able to work around that by specifying Node.js integration as true when the browser window (where this HTML file is embedded) was originally created in the main process.
function createAddItemWindow() {
// Create a new window
addItemWindown = new BrowserWindow({
width: 300,
height: 200,
title: 'Add Item',
// The lines below solved the issue
webPreferences: {
nodeIntegration: true
}
})}
That solved the issue for me. The solution was proposed here.