You are using a function, which is marked as deleted
.
Eg:
int doSomething( int ) = delete;
The =delete is a new feature of C++0x. It means the compiler should immediately stop compiling and complain "this function is deleted" once the user use such function.
If you see this error, you should check the function declaration for =delete
.
To know more about this new feature introduced in C++0x, check this out.
Do you mean like this?
import string
astr='a(b[c])d'
deleter=string.maketrans('()[]',' ')
print(astr.translate(deleter))
# a b c d
print(astr.translate(deleter).split())
# ['a', 'b', 'c', 'd']
print(list(reversed(astr.translate(deleter).split())))
# ['d', 'c', 'b', 'a']
print(' '.join(reversed(astr.translate(deleter).split())))
# d c b a
Depends a lot on your definition of what a "character" is. If "rune equals a character " is OK for your task (generally it isn't) then the answer by VonC is perfect for you. Otherwise, it should be probably noted, that there are few situations where the number of runes in a Unicode string is an interesting value. And even in those situations it's better, if possible, to infer the count while "traversing" the string as the runes are processed to avoid doubling the UTF-8 decode effort.
There seems to be a nasty edge case here: Ajax over congested wifi.
Ajax usually means that the KeepAlive has timed out after say 20 seconds. However, the wifi means that the (ideally fast) ajax connection has to make multiple round trips. Worse, the wifi often loses packets, and there are TCP retransmits. In this case, HTTPS performs really really badly!
z = list(zip(*tuple_list))
z[1][z[0].index('persimon')]
In Unix-like environments, I also recommend checking the actual running process command line:
$ ps aux | grep java
...
/usr/lib/jvm/java-8-openjdk-amd64/bin/java -Djava.util.logging.config.file=/srv/tomcat-instances/bla/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.awt.headless=true -Xmx4096M -XX:+UseConcMarkSweepGC -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n -Xmx4096m -Xms4096m -XX:MaxPermSize=2048m -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=8090 -Dcom.sun.management.jmxremote.rmi.port=8090 -Djava.rmi.server.hostname=localhost -Djava.endorsed.dirs=/opt/apache-tomcat-8.0.47/endorsed -classpath /opt/apache-tomcat-8.0.47/bin/bootstrap.jar:/opt/apache-tomcat-8.0.47/bin/tomcat-juli.jar -Dcatalina.base=/srv/tomcat-instances/bla -Dcatalina.home=/opt/apache-tomcat-8.0.47 -Djava.io.tmpdir=/tmp/tomcat8-bla-tmp org.apache.catalina.startup.Bootstrap start
...
One can run on subtle weird behaviors due to (operating system) environment variables and (Java) system properties being set to unexpected values. I had a situation where due to an outdated Tomcat setenv.sh
, A Tomcat 8 started with classes from a Tomcat 7 on the classpath. Make sure that in the process command line options such as -Dcatalina.base
, -Dcatalina.home
and -classpath
make sense.
http://locutus.io/php/strings/number_format/
module.exports = function number_format (number, decimals, decPoint, thousandsSep) { // eslint-disable-enter code hereline camelcase
// discuss at: http://locutus.io/php/number_format/
// original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// improved by: Kevin van Zonneveld (http://kvz.io)
// improved by: davook
// improved by: Brett Zamir (http://brett-zamir.me)
// improved by: Brett Zamir (http://brett-zamir.me)
// improved by: Theriault (https://github.com/Theriault)
// improved by: Kevin van Zonneveld (http://kvz.io)
// bugfixed by: Michael White (http://getsprink.com)
// bugfixed by: Benjamin Lupton
// bugfixed by: Allan Jensen (http://www.winternet.no)
// bugfixed by: Howard Yeend
// bugfixed by: Diogo Resende
// bugfixed by: Rival
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// revised by: Luke Smith (http://lucassmith.name)
// input by: Kheang Hok Chin (http://www.distantia.ca/)
// input by: Jay Klehr
// input by: Amir Habibi (http://www.residence-mixte.com/)
// input by: Amirouche
// example 1: number_format(1234.56)
// returns 1: '1,235'
// example 2: number_format(1234.56, 2, ',', ' ')
// returns 2: '1 234,56'
// example 3: number_format(1234.5678, 2, '.', '')
// returns 3: '1234.57'
// example 4: number_format(67, 2, ',', '.')
// returns 4: '67,00'
// example 5: number_format(1000)
// returns 5: '1,000'
// example 6: number_format(67.311, 2)
// returns 6: '67.31'
// example 7: number_format(1000.55, 1)
// returns 7: '1,000.6'
// example 8: number_format(67000, 5, ',', '.')
// returns 8: '67.000,00000'
// example 9: number_format(0.9, 0)
// returns 9: '1'
// example 10: number_format('1.20', 2)
// returns 10: '1.20'
// example 11: number_format('1.20', 4)
// returns 11: '1.2000'
// example 12: number_format('1.2000', 3)
// returns 12: '1.200'
// example 13: number_format('1 000,50', 2, '.', ' ')
// returns 13: '100 050.00'
// example 14: number_format(1e-8, 8, '.', '')
// returns 14: '0.00000001'
number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
var n = !isFinite(+number) ? 0 : +number
var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
var s = ''
var toFixedFix = function (n, prec) {
if (('' + n).indexOf('e') === -1) {
return +(Math.round(n + 'e+' + prec) + 'e-' + prec)
} else {
var arr = ('' + n).split('e')
var sig = ''
if (+arr[1] + prec > 0) {
sig = '+'
}
return (+(Math.round(+arr[0] + 'e' + sig + (+arr[1] + prec)) + 'e-' + prec)).toFixed(prec)
}
}
// @todo: for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec).toString() : '' + Math.round(n)).split('.')
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
}
return s.join(dec)
}
Or, you can ignore the error:
declare
column_exists exception;
pragma exception_init (column_exists , -01430);
begin
execute immediate 'ALTER TABLE db.tablename ADD columnname NVARCHAR2(30)';
exception when column_exists then null;
end;
/
use html5
's new attribute srcdoc
(srcdoc-polyfill) Docs
<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>
Browser support - Tested in the following browsers:
Microsoft Internet Explorer
6, 7, 8, 9, 10, 11
Microsoft Edge
13, 14
Safari
4, 5.0, 5.1 ,6, 6.2, 7.1, 8, 9.1, 10
Google Chrome
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24.0.1312.5 (beta), 25.0.1364.5 (dev), 55
Opera
11.1, 11.5, 11.6, 12.10, 12.11 (beta) , 42
Mozilla FireFox
3.0, 3.6, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 (beta), 50
An abstract class is a class that is declared abstract — it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
In other words, a class that is declared with abstract keyword, is known as abstract class in java. It can have abstract(method without body) and non-abstract methods (method with body).
Important Note:- Abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time Polymorphism is implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. You will see this feature in the below example
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){
System.out.println("running safely..");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Analoguously to the two options (homebrew / manual) posted by @brismuth, here's the MacPorts way:
Install the Android SDK:
sudo port install android
Run the SDK manager:
sh /opt/local/share/java/android-sdk-macosx/tools/android
As @brismuth suggested, uncheck everything but Android SDK Platform-tools
(optional)
Install the packages, accepting licenses. Close the SDK Manager.
Add platform-tools
to your path; in MacPorts, they're in /opt/local/share/java/android-sdk-macosx/platform-tools
. E.g., for bash:
echo 'export PATH=$PATH:/opt/local/share/java/android-sdk-macosx/platform-tools' >> ~/.bash_profile
Refresh your bash profile (or restart your terminal/shell):
source ~/.bash_profile
Start using adb:
adb devices
There is an open issue for this on their github page: https://github.com/npm/npm/issues/18712
This issue is most severe when developers are using different operating systems.
SDK developers prefer to define their own types using typedef. This allows changing underlying types only in one place, without changing all client code. It is important to follow this convention. DWORD is unlikely to be changed, but types like DWORD_PTR are different on different platforms, like Win32 and x64. So, if some function has DWORD parameter, use DWORD and not unsigned int, and your code will be compiled in all future windows headers versions.
Laravel ^5.7 includes new middleware to handle and redirect unauthenticated users.
It works well with "web" guard... of course the "login" route (or whatever you name your login route) should be defined in web.php.
the problem is when your are using custom guard. Different guard would redirect unauthenticated users to different route.
here's a quick workaround based on John's response (it works for me).
app/Http/Middleware/Authenticate.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* @var array
*/
protected $guards = [];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string[] ...$guards
* @return mixed
*
* @throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$guards)
{
$this->guards = $guards;
return parent::handle($request, $next, ...$guards);
}
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
if (in_array('admin', $this->guards)) {
return route('admin.login');
}
return route('login');
}
}
}
Source : Issue #26292
To set the value of the checkbox, you need to bind the v-model to a value. The checkbox will be checked if the value is truthy. In this case, you are iterating over modules
and each module
has a checked
property.
The following code will bind the checkbox with that property:
<input type="checkbox" v-model="module.checked" v-bind:id="module.id">
Notice that I removed v-bind:value="module.id"
. You shouldn't use v-model
and v-bind:value
on the same element. From the vue docs:
<input v-model="something">
is just syntactic sugar for:
<input v-bind:value="something" v-on:input="something = $event.target.value">
So, by using v-model
and v-bind:value
, you actually end up having v-bind:value
twice, which could lead to undefined behavior.
Do you mean to property files located in src/main/resources
? Then you should exclude them using the maven-resource-plugin. See the following page for details:
http://maven.apache.org/plugins/maven-resources-plugin/examples/include-exclude.html
A better way is using decorator instead of writing wrapper function by hand. Especially when you have a lot of functions to map, decorator will save your time by avoiding writing wrapper for every function. Usually a decorated function is not picklable, however we may use functools
to get around it. More disscusions can be found here.
Here the example
def unpack_args(func):
from functools import wraps
@wraps(func)
def wrapper(args):
if isinstance(args, dict):
return func(**args)
else:
return func(*args)
return wrapper
@unpack_args
def func(x, y):
return x + y
Then you may map it with zipped arguments
np, xlist, ylist = 2, range(10), range(10)
pool = Pool(np)
res = pool.map(func, zip(xlist, ylist))
pool.close()
pool.join()
Of course, you may always use Pool.starmap
in Python 3 (>=3.3) as mentioned in other answers.
I had the same question, but I also wanted the first line (header) to stay on top. So I needed to use the power of awk
cat dax-weekly.csv | awk '1 { last = NR; line[last] = $0; } END { print line[1]; for (i = last; i > 1; i--) { print line[i]; } }'
PS also works in cygwin or gitbash
I'd also like to point out that you can name each checkbox a different name, and have that name part of the actionresults parameters.
Example,
View:
<%= Html.CheckBox("Rs232CheckBox", false, new { @id = "rs232" })%>RS-232
<%= Html.CheckBox("Rs422CheckBox", false, new { @id = "rs422" })%>RS-422
Controller:
public ActionResults MyAction(bool Rs232CheckBox, bool Rs422CheckBox) {
...
}
The values from the view are passed to the action since the names are the same.
I know this solution isn't ideal for your project, but I thought I'd throw the idea out there.
import java.io.*;
public class FileRead {
public static void main(String[] args) throws IOException {
File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");
OutputStream oos = new FileOutputStream("test.pdf");
byte[] buf = new byte[8192];
InputStream is = new FileInputStream(f);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
oos.close();
System.out.println("stop");
is.close();
}
}
The easiest way so far. Hope this helps.
var jQueryObject = $('<div></div>').html( string ).children();
This creates a dummy jQuery object in which you can put the string as HTML. Then, you get the children only.
Just use the below formation###
rules_id = ["9","10"]
sql2 = "SELECT * FROM attendance_rules_staff WHERE id in"+str(tuple(rules_id))
note the str(tuple(rules_id))
.
you can use myfaces tomahawk component
http://myfaces.apache.org/tomahawk-project/tomahawk12/tagdoc/t_div.html
Adavantage of inner class--
Without existing of outer class inner class will not exist.
class car{
class wheel{
}
}
There are four types of inner class.
point ---
inorder to invoke normal inner class in static area of outer class.
Outer 0=new Outer();
Outer.Inner i= O.new Inner();
inorder to invoke normal inner class in instance area of outer class.
Inner i=new Inner();
inorder to invoke normal inner class in outside of outer class.
Outer 0=new Outer();
Outer.Inner i= O.new Inner();
inside Inner class This pointer to inner class.
this.member-current inner class
outerclassname.this--outer class
for inner class applicable modifier is -- public,default,
final,abstract,strictfp,+private,protected,static
outer$inner is the name of inner class name.
inner class inside instance method then we can acess static and instance field of outer class.
10.inner class inside static method then we can access only static field of
outer class.
class outer{
int x=10;
static int y-20;
public void m1() {
int i=30;
final j=40;
class inner{
public void m2() {
// have accees x,y and j
}
}
}
}
Just add parameters, split by comma:
UPDATE tablename SET column1 = "value1", column2 = "value2" ....
See also: mySQL manual on UPDATE
Python lists
translate to JSON arrays
. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict
:
>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
In my case the sub domain name causes the problem. Here are details
I used app_development.something.com
, here underscore(_
) sub domain is creating CORS error. After changing app_development
to app-development
it works fine.
You need to have
#include <string>
in the header file too.The forward declaration on it's own doesn't do enough.
Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:
#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H
/* header goes in here */
#endif
This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.
Can't comment on Susam Pal's answer but if you're dealing with spaces, I'd surround with quotes:
for f in *.jpg; do mv "$f" "`echo $f | sed s/\ /\-/g`"; done;
For me, this one worked without the sudo access.
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
For more reference, please follow https://gist.github.com/mxcl/323731
.blink_text {_x000D_
_x000D_
animation:1s blinker linear infinite;_x000D_
-webkit-animation:1s blinker linear infinite;_x000D_
-moz-animation:1s blinker linear infinite;_x000D_
_x000D_
color: red;_x000D_
}_x000D_
_x000D_
@-moz-keyframes blinker { _x000D_
0% { opacity: 1.0; }_x000D_
50% { opacity: 0.0; }_x000D_
100% { opacity: 1.0; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes blinker { _x000D_
0% { opacity: 1.0; }_x000D_
50% { opacity: 0.0; }_x000D_
100% { opacity: 1.0; }_x000D_
}_x000D_
_x000D_
@keyframes blinker { _x000D_
0% { opacity: 1.0; }_x000D_
50% { opacity: 0.0; }_x000D_
100% { opacity: 1.0; }_x000D_
}
_x000D_
<span class="blink_text">India's Largest portal</span>
_x000D_
Make sure the namespaces in Global.asax and Global.asax.cs are same. If they are different it will not throw any error but will not hit the breakpoint also because it is not executing application_start at all.
And if you want to add a row, you can use a dictionary:
df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)
which gives you:
age height name
0 9 2 Zed
From GeekInterview:
In J2EE application, modules are packaged as EAR, JAR, and WAR based on their functionality
JAR: EJB modules which contain enterprise java beans (class files) and EJB deployment descriptor are packed as JAR files with .jar extension
WAR: Web modules which contain Servlet class files, JSP Files, supporting files, GIF and HTML files are packaged as a JAR file with .war (web archive) extension
EAR: All the above files (.jar and .war) are packaged as a JAR file with .ear (enterprise archive) extension and deployed into Application Server.
I faced an another use case where I got the similar error.
When At first I got the error, I panicked, and removed /data/data/{package.name}
After that I tried, and my problem was still present.
Then I tried uninstall, it failed.
I then removed the apk file present in /system/app
(required root access), and tried uninstall and it was successfull.
After that I tried re-installing the apk, it worked.
<div id="location"></div>
<script>
window.onload = function () {
var startPos;
var geoOptions = {
maximumAge: 5 * 60 * 1000,
timeout: 10 * 1000,
enableHighAccuracy: true
}
var geoSuccess = function (position) {
startPos = position;
geocodeLatLng(startPos.coords.latitude, startPos.coords.longitude);
};
var geoError = function (error) {
console.log('Error occurred. Error code: ' + error.code);
// error.code can be:
// 0: unknown error
// 1: permission denied
// 2: position unavailable (error response from location provider)
// 3: timed out
};
navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);
};
function geocodeLatLng(lat, lng) {
var geocoder = new google.maps.Geocoder;
var latlng = {lat: parseFloat(lat), lng: parseFloat(lng)};
geocoder.geocode({'location': latlng}, function (results, status) {
if (status === 'OK') {
console.log(results)
if (results[0]) {
document.getElementById('location').innerHTML = results[0].formatted_address;
var street = "";
var city = "";
var state = "";
var country = "";
var zipcode = "";
for (var i = 0; i < results.length; i++) {
if (results[i].types[0] === "locality") {
city = results[i].address_components[0].long_name;
state = results[i].address_components[2].long_name;
}
if (results[i].types[0] === "postal_code" && zipcode == "") {
zipcode = results[i].address_components[0].long_name;
}
if (results[i].types[0] === "country") {
country = results[i].address_components[0].long_name;
}
if (results[i].types[0] === "route" && street == "") {
for (var j = 0; j < 4; j++) {
if (j == 0) {
street = results[i].address_components[j].long_name;
} else {
street += ", " + results[i].address_components[j].long_name;
}
}
}
if (results[i].types[0] === "street_address") {
for (var j = 0; j < 4; j++) {
if (j == 0) {
street = results[i].address_components[j].long_name;
} else {
street += ", " + results[i].address_components[j].long_name;
}
}
}
}
if (zipcode == "") {
if (typeof results[0].address_components[8] !== 'undefined') {
zipcode = results[0].address_components[8].long_name;
}
}
if (country == "") {
if (typeof results[0].address_components[7] !== 'undefined') {
country = results[0].address_components[7].long_name;
}
}
if (state == "") {
if (typeof results[0].address_components[6] !== 'undefined') {
state = results[0].address_components[6].long_name;
}
}
if (city == "") {
if (typeof results[0].address_components[5] !== 'undefined') {
city = results[0].address_components[5].long_name;
}
}
var address = {
"street": street,
"city": city,
"state": state,
"country": country,
"zipcode": zipcode,
};
document.getElementById('location').innerHTML = document.getElementById('location').innerHTML + "<br/>Street : " + address.street + "<br/>City : " + address.city + "<br/>State : " + address.state + "<br/>Country : " + address.country + "<br/>zipcode : " + address.zipcode;
console.log(address);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY">
</script>
1. Generalized Substring
To generalise the question and the answer of gniourf_gniourf (as this is what I was searching for), if you want to cut a range of characters from, say, 7th from the end to 3rd from the end, you can use this syntax:
${string: -7:4}
Where 4 is the length of course (7-3).
2. Alternative using cut
In addition, while the solution of gniourf_gniourf is obviously the best and neatest, I just wanted to add an alternative solution using cut:
echo $string | cut -c $((${#string}-2))-
Here, ${#string}
is the length of the string, and the "-" means cut to the end.
3. Alternative using awk
This solution instead uses the substring function of awk to select a substring which has the syntax substr(string, start, length)
going to the end if the length is omitted. length($string)-2)
thus picks up the last three characters.
echo $string | awk '{print substr($1,length($1)-2) }'
Easy.
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
Extras are retrieved on the other side via:
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.
}
Don't forget to add your new activity in the AndroidManifest.xml:
<activity android:label="@string/app_name" android:name="NextActivity"/>
Url.Action("Evil", model)
will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51
Just Add "JsonRequestBehavior.AllowGet" on your Json object.
I run across this and at the beginning I found it really confusing to be honest and I think this confusion comes from using the word "CMD" because in fact what goes there acts as argument. So after digging a little bit I understood how it works. Basically:
ENTRYPOINT --> what you specify here would be the command to be executed when you container starts. If you omit this definition docker will use /bin/sh -c bash
to run your container.
CMD --> these are the arguments appended to the ENTRYPOINT unless the user specifies some custom argument, i.e: docker run ubuntu <custom_cmd>
in this case instead of appending what's specified on the image in the CMD section, docker will run ENTRYPOINT <custom_cmd>
. In case ENTRYPOINT has not been specified, what goes here will be passed to /bin/sh -c
acting in fact as the command to be executed when starting the container.
As everything it's better to explain what's going on by examples. So let's say I create a simple docker image by using the following specification Dockerfile:
From ubuntu
ENTRYPOINT ["sleep"]
Then I build it by running the following:
docker build . -t testimg
This will create a container that everytime you run it sleeps. So If I run it as following:
docker run testimg
I'll get the following:
sleep: missing operand
Try 'sleep --help' for more information.
This happens because the entry point is the "sleep" command which needs an argument. So to fix this I'll just provide the amount to sleep:
docker run testimg 5
This will run correctly and as consequence the container will run, sleeps 5 seconds and exits. As we can see in this example docker just appended what goes after the image name to the entry point binary docker run testimg <my_cmd>
. What happens if we want to pass a default value (default argument) to the entry point? in this case we just need to specify it in the CMD section, for example:
From ubuntu
ENTRYPOINT ["sleep"]
CMD ["10"]
In this case if the user doesn't pass any argument the container will use the default value (10) and pass it to entry point sleep.
Now let's use just CMD and omit ENTRYPOINT definition:
FROM ubuntu
CMD ["sleep", "5"]
If we rebuild and run this image it will basically sleeps for 5 seconds.
So in summary, you can use ENTRYPOINT in order to make your container acts as an executable. You can use CMD to provide default arguments to your entry point or to run a custom command when starting your container that can be overridden from outside by user.
Another great solution to debug the Network calls before redirecting to other pages is to select the beforeunload
event break point
This way you assure to break the flow right before it redirecting it to another page, this way all network calls, network data and console logs are still there.
This solution is best when you want to check what is the response of the calls
P.S: You can also use XHR break points if you want to stop right before a specific call or any call (see image example)
They are taking a 'shotgun' approach to referencing the font. The browser will attempt to match each font name with any installed fonts on the user's machine (in the order they have been listed).
In your example "HelveticaNeue-Light"
will be tried first, if this font variant is unavailable the browser will try "Helvetica Neue Light"
and finally "Helvetica Neue"
.
As far as I'm aware "Helvetica Neue"
isn't considered a 'web safe font', which means you won't be able to rely on it being installed for your entire user base. It is quite common to define "serif"
or "sans-serif"
as a final default position.
In order to use fonts which aren't 'web safe' you'll need to use a technique known as font embedding. Embedded fonts do not need to be installed on a user's computer, instead they are downloaded as part of the page. Be aware this increases the overall payload (just like an image does) and can have an impact on page load times.
A great resource for free fonts with open-source licenses is Google Fonts. (You should still check individual licenses before using them.) Each font has a download link with instructions on how to embed them in your website.
You are not returning a response object from your view my_form_post
. The function ends with implicit return None
, which Flask does not like.
Make the function my_form_post
return an explicit response, for example
return 'OK'
at the end of the function.
As per @Nitsew's answer, Create your personal access token and use your token as your username and enter with blank password.
Later you won't need any credentials to access all your private repo(s).
Try this one.
String[] array1= new String[]{};
System.out.println(array1.length);
String[] array2= new String[0];
System.out.println(array2.length);
Note: there is no byte code difference between new String[]{}; and new String[0];
new String[]{}
is array initialization with values.
new String[0];
is array declaration(only allocating memory)
new String[10]{};
is not allowed because new String[10]{ may be here 100 values};
I'd like to suggest a yet-unmentioned solution: use CSS3's calc()
to mix %
and px
units. calc()
has excellent support nowadays, and it allows for fast construction of quite complex layouts.
Here's a JSFiddle link for the code below.
HTML:
<div class="sidebar">
sidebar fixed width
</div>
<div class="content">
content flexible width
</div>
CSS:
.sidebar {
width: 180px;
float: right;
background: green;
}
.content {
width: calc(100% - 180px);
background: orange;
}
And here's another JSFiddle demonstrating this concept applied to a more complex layout. I used SCSS here since its variables allow for flexible and self-descriptive code, but the layout can be easily re-created in pure CSS if having "hard-coded" values is not an issue.
And when you use a case :
CASE
WHEN TB1.COD IS NULL THEN
TB1.COD || ' - ' || TB1.NAME
ELSE
TB1.COD || ' - ' || TB1.NAME || ' - ' || TB.NM_TABELAFRETE
END AS NR_FRETE,
Using Xcode 12.3 Distribute App and xcodebuild both got stuck today at this point.
I finally was able to solve this. Peeking around my system I found 3 versions of iTMSTransporter.
Printing the version of each using ./iTMSTransporter -version
gives the following results:
/Applications/Transporter.app/Contents/itms/bin/
has version 2.0.0
/Applications/Xcode.app/Contents/SharedFrameworks/ContentDeliveryServices.framework/Versions/A/itms/bin/
has version 2.1.0
/usr/local/itms/bin/
has version version 1.9.3
So it looks that old version in /usr/local/itms
was used by Xcode. After deleting /usr/local/itms
I was able to upload my binary within Xcode 12.2 and using the xcodebuild
command line tool.
I've decided to give an answer to this question because I think it can be solved using a simpler syntax than the convoluted try-catch block. The Laravel documentation is pretty brief on this subject.
Instead of using try-catch, you can just use the DB::transaction(){...}
wrapper like this:
// MyController.php
public function store(Request $request) {
return DB::transaction(function() use ($request) {
$user = User::create([
'username' => $request->post('username')
]);
// Add some sort of "log" record for the sake of transaction:
$log = Log::create([
'message' => 'User Foobar created'
]);
// Lets add some custom validation that will prohibit the transaction:
if($user->id > 1) {
throw AnyException('Please rollback this transaction');
}
return response()->json(['message' => 'User saved!']);
});
};
You should then see that the User and the Log record cannot exist without eachother.
Some notes on the implementation above:
return
the transaction, so that you can use the response()
you return within its callback.throw
an exception if you want the transaction to be rollbacked (or have a nested function that throws the exception for you automatically, like an SQL exception from within Eloquent).id
, updated_at
, created_at
and any other fields are AVAILABLE AFTER CREATION for the $user
object (for the duration of this transaction). The transaction will run through any of the creation logic you have. HOWEVER, the whole record is discarded when the AnyException
is thrown. This means that for instance an auto-increment column for id
does get incremented on failed transactions.Tested on Laravel 5.8
You can add comments in Vim's configuration file by either:
" brief descriptiion of command
or:
"" commended command
Taken from here
Have you checked these official docs?
HostListener - Declares a host listener. Angular will invoke the decorated method when the host element emits the specified event.
@HostListener
- will listen to the event emitted by the host element that's declared with @HostListener
.
HostBinding - Declares a host property binding. Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive.
@HostBinding
- will bind the property to the host element, If a binding changes, HostBinding
will update the host element.
NOTE: Both links have been removed recently. The "HostBinding-HostListening" portion of the style guide may be a useful alternative until the links return.
Here's a simple code example to help picture what this means:
DEMO : Here's the demo live in plunker - "A simple example about @HostListener & @HostBinding"
role
property -- declared with @HostBinding
-- to the host's element
role
is an attribute, since we're using attr.role
.<p myDir>
becomes <p mydir="" role="admin">
when you view it in developer tools.onClick
event declared with @HostListener
, attached to the component's host element, changing role
with each click.
<p myDir>
is clicked is that its opening tag changes from <p mydir="" role="admin">
to <p mydir="" role="guest">
and back.directives.ts
import {Component,HostListener,Directive,HostBinding,Input} from '@angular/core';
@Directive({selector: '[myDir]'})
export class HostDirective {
@HostBinding('attr.role') role = 'admin';
@HostListener('click') onClick() {
this.role= this.role === 'admin' ? 'guest' : 'admin';
}
}
AppComponent.ts
import { Component,ElementRef,ViewChild } from '@angular/core';
import {HostDirective} from './directives';
@Component({
selector: 'my-app',
template:
`
<p myDir>Host Element
<br><br>
We have a (HostListener) listening to this host's <b>click event</b> declared with @HostListener
<br><br>
And we have a (HostBinding) binding <b>the role property</b> to host element declared with @HostBinding
and checking host's property binding updates.
If any property change is found I will update it.
</p>
<div>View this change in the DOM of the host element by opening developer tools,
clicking the host element in the UI.
The role attribute's changes will be visible in the DOM.</div>
`,
directives: [HostDirective]
})
export class AppComponent {}
Those CORS headers do not support *
as value, the only way is to replace *
with this:
Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With
.htaccess
Example (CORS Included):<IfModule mod_headers.c>
Header unset Connection
Header unset Time-Zone
Header unset Keep-Alive
Header unset Access-Control-Allow-Origin
Header unset Access-Control-Allow-Headers
Header unset Access-Control-Expose-Headers
Header unset Access-Control-Allow-Methods
Header unset Access-Control-Allow-Credentials
Header set Connection keep-alive
Header set Time-Zone "Asia/Jerusalem"
Header set Keep-Alive timeout=100,max=500
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
Header set Access-Control-Expose-Headers "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
Header set Access-Control-Allow-Methods "CONNECT, DEBUG, DELETE, DONE, GET, HEAD, HTTP, HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2, OPTIONS, ORIGIN, ORIGINS, PATCH, POST, PUT, QUIC, REST, SESSION, SHOULD, SPDY, TRACE, TRACK"
Header set Access-Control-Allow-Credentials "true"
Header set DNT "0"
Header set Accept-Ranges "bytes"
Header set Vary "Accept-Encoding"
Header set X-UA-Compatible "IE=edge,chrome=1"
Header set X-Frame-Options "SAMEORIGIN"
Header set X-Content-Type-Options "nosniff"
Header set X-Xss-Protection "1; mode=block"
</IfModule>
Why Access-Control-Allow-Headers
, Access-Control-Expose-Headers
, Access-Control-Allow-Methods
values are super long?
Those do not support the *
syntax, so I've collected the most common (and exotic) headers from around the web, in various formats #1 #2 #3 (and I will update the list from time to time)
Why do you use Header unset ______
syntax?
GoDaddy servers (which my website is hosted on..) have a weird bug where if the headers are already set, the previous value will join the existing one.. (instead of replacing it) this way I "pre-clean" existing values (really just a a quick && dirty solution)
Is it safe for me to use 'as-is'?
Well.. mostly the answer would be YES since the .htaccess
is limiting the headers to the scripts (PHP, HTML, ...) and resources (.JPG, .JS, .CSS) served from the following "folder"-location. You optionally might want to remove the Access-Control-Allow-Methods
lines. Also Connection
, Time-Zone
, Keep-Alive
and DNT
, Accept-Ranges
, Vary
, X-UA-Compatible
, X-Frame-Options
, X-Content-Type-Options
and X-Xss-Protection
are just a suggestion I'm using for my online-service.. feel free to remove those too...
taken from my comment above
If I understand you correctly you are asking about including nested properties. If so :
.Include(x => x.ApplicationsWithOverrideGroup.NestedProp)
or
.Include("ApplicationsWithOverrideGroup.NestedProp")
or
.Include($"{nameof(ApplicationsWithOverrideGroup)}.{nameof(NestedProp)}")
Noticed your comment about using it for email validation and needing a plugin, the validation plugin may help you, its located at http://bassistance.de/jquery-plugins/jquery-plugin-validation/, it comes with a e-mail rule as well.
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
Objects are eligable for garbage collection once they go out of scope become unreachable (thanks ben!). The memory won't be freed unless the garbage collector believes you are running out of memory.
For managed resources, the garbage collector will know when this is, and you don't need to do anything.
For unmanaged resources (such as connections to databases or opened files) the garbage collector has no way of knowing how much memory they are consuming, and that is why you need to free them manually (using dispose, or much better still the using block)
If objects are not being freed, either you have plenty of memory left and there is no need, or you are maintaining a reference to them in your application, and therefore the garbage collector will not free them (in case you actually use this reference you maintained)
Windows users, add this to PHP.ini:
curl.cainfo = "C:/cacert.pem";
Path needs to be changed to your own and you can download cacert.pem from a google search
(yes I know its a CentOS question)
If this is incidental, a simple if
is all you need. If this happens in many places, you might want to consider these two:
Something like:
[Between("parameter", 0, 100)]
public void Foo(int parameter)
{
}
i found this help:
git checkout --orphan empty.branch.name
git rm --cached -r .
echo "init empty branch" > README.md
git add README.md
git commit -m "init empty branch"
Fetch id basing on name
{
"roles": [
{
"id": 1,
"name": "admin",
},
{
"id": 3,
"name": "manager",
}
]
}
fetchIdBasingOnRole() {
const self = this;
if (this.employee.roles) {
var roleid = _.result(
_.find(this.getRoles, function(obj) {
return obj.name === self.employee.roles;
}),
"id"
);
}
return roleid;
},
May you have taken permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
BUT
hi guys after one day searching on web finally i solve problem with below source code hope to help you
public UploadResult UploadFile(string fileAddress)
{
HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new StringContent("fileToUpload");
form.Add(content, "fileToUpload");
var stream = new FileStream(fileAddress, FileMode.Open);
content = new StreamContent(stream);
var fileName =
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "name",
FileName = Path.GetFileName(fileAddress),
};
form.Add(content);
HttpResponseMessage response = null;
var url = new Uri("http://192.168.10.236:2000/api/Upload2");
response = (client.PostAsync(url, form)).Result;
}
Yes. In fact, all instance methods in Java are virtual by default. Only certain methods are not virtual:
Here are some examples:
"Normal" virtual functions
The following example is from an old version of the wikipedia page mentioned in another answer.
import java.util.*;
public class Animal
{
public void eat()
{
System.out.println("I eat like a generic Animal.");
}
public static void main(String[] args)
{
List<Animal> animals = new LinkedList<Animal>();
animals.add(new Animal());
animals.add(new Fish());
animals.add(new Goldfish());
animals.add(new OtherAnimal());
for (Animal currentAnimal : animals)
{
currentAnimal.eat();
}
}
}
class Fish extends Animal
{
@Override
public void eat()
{
System.out.println("I eat like a fish!");
}
}
class Goldfish extends Fish
{
@Override
public void eat()
{
System.out.println("I eat like a goldfish!");
}
}
class OtherAnimal extends Animal {}
Output:
I eat like a generic Animal. I eat like a fish! I eat like a goldfish! I eat like a generic Animal.
Example with virtual functions with interfaces
Java interface methods are all virtual. They must be virtual because they rely on the implementing classes to provide the method implementations. The code to execute will only be selected at run time.
For example:
interface Bicycle { //the function applyBrakes() is virtual because
void applyBrakes(); //functions in interfaces are designed to be
} //overridden.
class ACMEBicycle implements Bicycle {
public void applyBrakes(){ //Here we implement applyBrakes()
System.out.println("Brakes applied"); //function
}
}
Example with virtual functions with abstract classes.
Similar to interfaces Abstract classes must contain virtual methods because they rely on the extending classes' implementation. For Example:
abstract class Dog {
final void bark() { //bark() is not virtual because it is
System.out.println("woof"); //final and if you tried to override it
} //you would get a compile time error.
abstract void jump(); //jump() is a "pure" virtual function
}
class MyDog extends Dog{
void jump(){
System.out.println("boing"); //here jump() is being overridden
}
}
public class Runner {
public static void main(String[] args) {
Dog dog = new MyDog(); // Create a MyDog and assign to plain Dog variable
dog.jump(); // calling the virtual function.
// MyDog.jump() will be executed
// although the variable is just a plain Dog.
}
}
The above answers won't let you quote inside the quotes. This solution will:
sudo -su nobody umask 0000 \; mkdir -p "$targetdir"
Both the umask command and the mkdir-command runs in with the 'nobody' user.
Ref and event bus both has issues when your control render is affected by v-if
. So, I decided to go with a simpler method.
The idea is using an array as a queue to send methods that needs to be called to the child component. Once the component got mounted, it will process this queue. It watches the queue to execute new methods.
(Borrowing some code from Desmond Lua's answer)
Parent component code:
import ChildComponent from './components/ChildComponent'
new Vue({
el: '#app',
data: {
item: {},
childMethodsQueue: [],
},
template: `
<div>
<ChildComponent :item="item" :methods-queue="childMethodsQueue" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.childMethodsQueue.push({name: ChildComponent.methods.save.name, params: {}})
}
},
components: { ChildComponent },
})
This is code for ChildComponent
<template>
...
</template>
<script>
export default {
name: 'ChildComponent',
props: {
methodsQueue: { type: Array },
},
watch: {
methodsQueue: function () {
this.processMethodsQueue()
},
},
mounted() {
this.processMethodsQueue()
},
methods: {
save() {
console.log("Child saved...")
},
processMethodsQueue() {
if (!this.methodsQueue) return
let len = this.methodsQueue.length
for (let i = 0; i < len; i++) {
let method = this.methodsQueue.shift()
this[method.name](method.params)
}
},
},
}
</script>
And there is a lot of room for improvement like moving processMethodsQueue
to a mixin...
In addition to the provided answer, there are more details to navigate
. From the function's comments:
/**
* Navigate based on the provided array of commands and a starting point.
* If no starting route is provided, the navigation is absolute.
*
* Returns a promise that:
* - resolves to 'true' when navigation succeeds,
* - resolves to 'false' when navigation fails,
* - is rejected when an error happens.
*
* ### Usage
*
* ```
* router.navigate(['team', 33, 'user', 11], {relativeTo: route});
*
* // Navigate without updating the URL
* router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
* ```
*
* In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
* URL.
*/
The Router Guide has more details on programmatic navigation.
I had the same issue too, the problem is exacerbated with the download link now only working for Visual Studio 2017, and installing the package from the download link did nothing for VS2015, although it took up 5gB of space.
I looked everywhere on how to do it with the Nu Get package manager and I couldn't find the solution.
It turns out it's even simpler than that, all you have to do is right-click the project or solution in the Solution Explorer from within Visual Studio, and click "Install Missing Components"
The best way to do so with JS is using preventDefault() function. Consider the code below for reference:
function loadForm(){
var loginForm = document.querySelector('form'); //Selecting the form
loginForm.addEventListener('submit', login); //looking for submit
}
function login(e){
e.preventDefault(); //to stop form action i.e. submit
}
@firedrawndagger: to list field names/column headers iterate through the recordset Fields collection and insert the name:
Dim myRS as ADODB.Recordset
Dim fld as Field
Dim strFieldName as String
For Each fld in myRS.Fields
Activesheet.Selection = fld.Name
[Some code that moves to next column]
Next
It seems the original author has found their solution, but for anyone else who gets here looking to add actual custom headers, if you have access to mod the generated Protocol code you can override GetWebRequest
:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
System.Net.WebRequest request = base.GetWebRequest(uri);
request.Headers.Add("myheader", "myheader_value");
return request;
}
Make sure you remove the DebuggerStepThroughAttribute
attribute if you want to step into it.
If you already have the string, you can use this function:
bool isNumber( const string& s )
{
bool hitDecimal=0;
for( char c : s )
{
if( c=='.' && !hitDecimal ) // 2 '.' in string mean invalid
hitDecimal=1; // first hit here, we forgive and skip
else if( !isdigit( c ) )
return 0 ; // not ., not
}
return 1 ;
}
I saw this and in CSS3 you can now place code in like this. Lets say I want it to cover the whole background I would do something like this. Then with hsla(0,0%,100%,0.70)
or rgba you use a white background with whatever percentage saturation or opacity to get the look you desire.
.body{
background-attachment: fixed;
background-image: url(../images/Store1.jpeg);
display: block;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 1;
background-color: hsla(0,0%,100%,0.70);
background-blend-mode: overlay;
background-repeat: no-repeat;
}
I draw your attention to the ArrayList.add
documentation, which says it throws IndexOutOfBoundsException
- if the index is out of range (index < 0 || index > size()
)
Check the size()
of your list before you call list.add(1, object1)
You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
NOTE
willSet
anddidSet
observers are not called when a property is set in an initializer before delegation takes place
if(window.location.href.indexOf("?added-to-cart=555") >= 0)
It's window.location.href
, not window.location
.
Although the answer with "!" was chosen as the correct answer, this is NOT true. I´m not sure about Windows Explorer in Windows 10/8.1/8, but I am certain concerning Windows 7 and XP.
The character that moves your filename to the very top is "'" (alt+39), and second best is "-" (the minus sign).
But sorting order in Windows Explorer is more complicated - it depends on the filename-lenght also, and numbers are treated very special.
The second character (and the following) is treated different. Here you often go best with a " " (spacebar), followed by the characters mentioned above, but you´ll have to try out, because it´s not so easy to find out the exact algorithm:
Here is an example for the correct sorting order for your understanding:
Another example:
Same filelenght:
Finally the very special logic when it comes to numbers:
But nevertheless: Renaming folders or files this way, you can quickly find what you are searching for.
Predicate<Client> hasSameNameAsOneUser =
c -> users.stream().anyMatch(u -> u.getName().equals(c.getName()));
return clients.stream()
.filter(hasSameNameAsOneUser)
.collect(Collectors.toList());
But this is quite inefficient, because it's O(m * n). You'd better create a Set of acceptable names:
Set<String> acceptableNames =
users.stream()
.map(User::getName)
.collect(Collectors.toSet());
return clients.stream()
.filter(c -> acceptableNames.contains(c.getName()))
.collect(Collectors.toList());
Also note that it's not strictly equivalent to the code you have (if it compiled), which adds the same client twice to the list if several users have the same name as the client.
This stratify
parameter makes a split so that the proportion of values in the sample produced will be the same as the proportion of values provided to parameter stratify
.
For example, if variable y
is a binary categorical variable with values 0
and 1
and there are 25% of zeros and 75% of ones, stratify=y
will make sure that your random split has 25% of 0
's and 75% of 1
's.
On windows, use https://github.com/Zapotek/raw2vmdk to convert raw files created by dd or winhex to vmdk. raw2vmdk v0.1.3.2 has a bug - once the vmdk file is created, edit the vmdk file and fix the path to the raw file (in my case instead of D:\Temp\flash_16gb.raw (created by winhex) the generated path was D:Tempflash_16gb.raw). Then, open it in a vmware virtual machine version 6.5-7 (5.1 was refusing to attach the vmdk harddrive). howgh!
Just use the result from the FOR
command. For example (inside a batch file):
for /F "delims=" %%I in ('dir /b /a-d /od FILESA*') do (echo %%I)
You can use the %%I
as the value you want. Just like this: %%I
.
And in advance the %%I
does not have any spaces or CR characters and can be used for comparisons!!
If you are using IntelliJ IDE just right click on resources package and go to new and then select Resource Boundle it automatically create a .properties file for you. This did work for me .
We could type our variable with an explicit return type:
const script: HTMLScriptElement = document.getElementsByName(id).item(0);
Or assert as (needed with TSX):
const script = document.getElementsByName(id).item(0) as HTMLScriptElement;
Or in simpler cases assert with angle-bracket syntax.
A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler.
Documentation:
Here you have to just add jar file in lib jsoup in your application and then use this code.
import org.jsoup.Jsoup;
public class Encoder {
public static void main(String args[]) {
String s = Jsoup.parse("<Français>").text();
System.out.print(s);
}
}
Link to download jsoup: http://jsoup.org/download
I had referenced this article and many others and did not find a clear cut concise response to help. I am offering my discovery, arrived at with some references from this thread, in the following:
Spring-Boot version: 1.3.5.RELEASE
Spring-Core version: 4.2.6.RELEASE
Dependency Management: Brixton.SR1
The following is the pertinent yaml excerpt:
tools:
toolList:
-
name: jira
matchUrl: http://someJiraUrl
-
name: bamboo
matchUrl: http://someBambooUrl
I created a Tools.class:
@Component
@ConfigurationProperties(prefix = "tools")
public class Tools{
private List<Tool> toolList = new ArrayList<>();
public Tools(){
//empty ctor
}
public List<Tool> getToolList(){
return toolList;
}
public void setToolList(List<Tool> tools){
this.toolList = tools;
}
}
I created a Tool.class:
@Component
public class Tool{
private String name;
private String matchUrl;
public Tool(){
//empty ctor
}
public String getName(){
return name;
}
public void setName(String name){
this.name= name;
}
public String getMatchUrl(){
return matchUrl;
}
public void setMatchUrl(String matchUrl){
this.matchUrl= matchUrl;
}
@Override
public String toString(){
StringBuffer sb = new StringBuffer();
String ls = System.lineSeparator();
sb.append(ls);
sb.append("name: " + name);
sb.append(ls);
sb.append("matchUrl: " + matchUrl);
sb.append(ls);
}
}
I used this combination in another class through @Autowired
@Component
public class SomeOtherClass{
private Logger logger = LoggerFactory.getLogger(SomeOtherClass.class);
@Autowired
private Tools tools;
/* excluded non-related code */
@PostConstruct
private void init(){
List<Tool> toolList = tools.getToolList();
if(toolList.size() > 0){
for(Tool t: toolList){
logger.info(t.toString());
}
}else{
logger.info("*****----- tool size is zero -----*****");
}
}
/* excluded non-related code */
}
And in my logs the name and matching url's were logged. This was developed on another machine and thus I had to retype all of the above so please forgive me in advance if I inadvertently mistyped.
I hope this consolidation comment is helpful to many and I thank the previous contributors to this thread!
FYI you dont have string datatype in C. Use array of characters to store the value and manipulate it. Change your variable c into an array of characters and use it inside a loop to get values.
char c[10];
int i=0;
while(i!=10)
{
c[i]=fgetc(fp);
i++;
}
The other way to do is to use pointers and allocate memory dynamically and assign values.
As per your question vertical listing have a scrollbar effect.
CSS / HTML :
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<header>header area</header>_x000D_
<nav>_x000D_
<ul>_x000D_
<li>Link 1</li>_x000D_
<li>Link 2</li>_x000D_
<li>Link 3</li>_x000D_
<li>Link 4</li>_x000D_
<li>Link 5</li>_x000D_
<li>Link 6</li> _x000D_
<li>Link 7</li> _x000D_
<li>Link 8</li>_x000D_
<li>Link 9</li>_x000D_
<li>Link 10</li>_x000D_
<li>Link 11</li>_x000D_
<li>Link 13</li>_x000D_
<li>Link 13</li>_x000D_
_x000D_
</ul>_x000D_
</nav>_x000D_
_x000D_
<footer>footer area</footer>_x000D_
</body>_x000D_
</html>
_x000D_
try this! syntax less lines and even more compact! don't forget to add the properties you want to add with this approach!
cmd.Parameters.Add(new SqlParameter{SqlValue=(object)username??DBNull.Value,ParameterName="user" } );
For the question:
How to save Console.Writeline Outputs to text file?
I would use Console.SetOut
as others have mentioned.
However, it looks more like you are keeping track of your program flow. I would consider using Debug
or Trace
for keeping track of the program state.
It works similar the console except you have more control over your input such as WriteLineIf
.
Debug
will only operate when in debug mode where as Trace
will operate in both debug or release mode.
They both allow for listeners such as output files or the console.
TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(tr1);
TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));
Debug.Listeners.Add(tr2);
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)
Set the ViewController's (the one holding the UIScrollView) size to Freeform in the size inspector in Interface Builder and all should work.
Freeform setting in Size inspector in Interface Builder for the containing UIViewcontroller
Some compilers provide access to the integer overflow flag in the CPU which you could then test but this isn't standard.
You could also test for the possibility of overflow before you perform the multiplication:
if ( b > ULONG_MAX / a ) // a * b would overflow
Check your imports. There could be two classes with the same name. Either from your code or from a library you are using. Personally that was the issue.
try
$('#select_all').click( function() {
$('#countries option').each(function(){
$(this).attr('selected', 'selected');
});
});
this will give you more scope in the future to write things like
$('#select_all').click( function() {
$('#countries option').each(function(){
if($(this).attr('something') != 'omit parameter')
{
$(this).attr('selected', 'selected');
}
});
});
Basically allows for you to do a select all EU members or something if required later down the line
The only issue with promises is that IE doesn't support them. Edge does, but there's plenty of IE 10 and 11 out there: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise (compatibility at the bottom)
So, JavaScript is single-threaded. If you're not making an asynchronous call, it will behave predictably. The main JavaScript thread will execute one function completely before executing the next one, in the order they appear in the code. Guaranteeing order for synchronous functions is trivial - each function will execute completely in the order it was called.
Think of the synchronous function as an atomic unit of work. The main JavaScript thread will execute it fully, in the order the statements appear in the code.
But, throw in the asynchronous call, as in the following situation:
showLoadingDiv(); // function 1
makeAjaxCall(); // function 2 - contains async ajax call
hideLoadingDiv(); // function 3
This doesn't do what you want. It instantaneously executes function 1, function 2, and function 3. Loading div flashes and it's gone, while the ajax call is not nearly complete, even though makeAjaxCall()
has returned. THE COMPLICATION is that makeAjaxCall()
has broken its work up into chunks which are advanced little by little by each spin of the main JavaScript thread - it's behaving asychronously. But that same main thread, during one spin/run, executed the synchronous portions quickly and predictably.
So, the way I handled it: Like I said the function is the atomic unit of work. I combined the code of function 1 and 2 - I put the code of function 1 in function 2, before the asynch call. I got rid of function 1. Everything up to and including the asynchronous call executes predictably, in order.
THEN, when the asynchronous call completes, after several spins of the main JavaScript thread, have it call function 3. This guarantees the order. For example, with ajax, the onreadystatechange event handler is called multiple times. When it reports it's completed, then call the final function you want.
I agree it's messier. I like having code be symmetric, I like having functions do one thing (or close to it), and I don't like having the ajax call in any way be responsible for the display (creating a dependency on the caller). BUT, with an asynchronous call embedded in a synchronous function, compromises have to be made in order to guarantee order of execution. And I have to code for IE 10 so no promises.
Summary: For synchronous calls, guaranteeing order is trivial. Each function executes fully in the order it was called. For a function with an asynchronous call, the only way to guarantee order is to monitor when the async call completes, and call the third function when that state is detected.
For a discussion of JavaScript threads, see: https://medium.com/@francesco_rizzi/javascript-main-thread-dissected-43c85fce7e23 and https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
Also, another similar, highly rated question on this subject: How should I call 3 functions in order to execute them one after the other?
Security Warning: AES-256-CBC does not provide authenticated encryption and is vulnerable to padding oracle attacks. You should use something like age instead.
Encrypt:
openssl aes-256-cbc -a -salt -in secrets.txt -out secrets.txt.enc
Decrypt:
openssl aes-256-cbc -d -a -in secrets.txt.enc -out secrets.txt.new
Alternatively, below commands also worked for me:
mvn -s settings.xml eclipse:clean
mvn -s settings.xml eclipse:eclipse
You need to convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
Actually you can fix it with following steps -
cls.__dict__
{'isFilled':True}
or {'isFilled':False}
depending upon what you have set.del cls.__dict__['isFilled']
In this case, we delete the entry which overrides the method as mentioned by BrenBarn.
a csv-file is just like any other file a stream of characters. the getline reads from the file up to a delimiter however in your case the delimiter for the last item is not ' ' as you assume
getline(file, genero, ' ') ;
it is newline \n
so change that line to
getline(file, genero); // \n is default delimiter
You can definitely go for typeid(x).name()
where x is the variable name. It actually returns a const char pointer to the data type. Now, look at the following code.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n = 36;
char c = 'A';
double d = 1.2;
if(*(typeid(n).name()) == 'i'){
cout << "I am an Integer variable" << endl;
}
if(*((char *) typeid(d).name()) == 'd'){
cout << "I am a Double variable" << endl;
}
if(*((char *) typeid(c).name()) == 'c'){
cout << "I am a Char variable" << endl;
}
return 0;
}
Notice how first and second both if works.
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
I had the same issue today. My problem was solved my moving META-INF to the resources folder.
Couldn't you just pass the a name attribute and wrap it in a form?
<form id="form" action="do_stuff.php" method="post">
<select id="select_catalog" name="select_catalog_query">
<?php <<<INSERT THE SELECT OPTION LOOP>>> ?>
</select>
</form>
And then look for $_POST['select_catalog_query']
?
OP's sample code is incorrect.
Endian conversion works at the bit and 8-bit byte level. Most endian issues deal with the byte level. OP code is doing a endian change at the 4-bit nibble level. Recommend instead:
// Swap endian (big to little) or (little to big)
uint32_t num = 9;
uint32_t b0,b1,b2,b3;
uint32_t res;
b0 = (num & 0x000000ff) << 24u;
b1 = (num & 0x0000ff00) << 8u;
b2 = (num & 0x00ff0000) >> 8u;
b3 = (num & 0xff000000) >> 24u;
res = b0 | b1 | b2 | b3;
printf("%" PRIX32 "\n", res);
If performance is truly important, the particular processor would need to be known. Otherwise, leave it to the compiler.
[Edit] OP added a comment that changes things.
"32bit numerical value represented by the hexadecimal representation (st uv wx yz) shall be recorded in a four-byte field as (st uv wx yz)."
It appears in this case, the endian of the 32-bit number is unknown and the result needs to be store in memory in little endian order.
uint32_t num = 9;
uint8_t b[4];
b[0] = (uint8_t) (num >> 0u);
b[1] = (uint8_t) (num >> 8u);
b[2] = (uint8_t) (num >> 16u);
b[3] = (uint8_t) (num >> 24u);
[2016 Edit] Simplification
... The type of the result is that of the promoted left operand.... Bitwise shift operators C11 §6.5.7 3
Using a u
after the shift constants (right operands) results in the same as without it.
b3 = (num & 0xff000000) >> 24u;
b[3] = (uint8_t) (num >> 24u);
// same as
b3 = (num & 0xff000000) >> 24;
b[3] = (uint8_t) (num >> 24);
Since Python is interpreted and run in C, it is possible to set colors without a module.
You can define a class for colors like this:
class color:
PURPLE = '\033[1;35;48m'
CYAN = '\033[1;36;48m'
BOLD = '\033[1;37;48m'
BLUE = '\033[1;34;48m'
GREEN = '\033[1;32;48m'
YELLOW = '\033[1;33;48m'
RED = '\033[1;31;48m'
BLACK = '\033[1;30;48m'
UNDERLINE = '\033[4;37;48m'
END = '\033[1;37;0m'
When writing code, you can simply write:
print(color.BLUE + "hello friends" + color.END)
Note that the color you choose will have to be capitalized like your class definition, and that these are color choices that I personally find satisfying. For a fuller array of color choices and, indeed, background choices as well, please see: https://gist.github.com/RabaDabaDoba/145049536f815903c79944599c6f952a.
This is code for C, but can easily be adapted to Python once you realize how the code is written.
Take BLUE for example, since that is what you are wanting to display.
BLUE = '033[1;37;48m'
\033 tells Python to break and pay attention to the following formatting.
1 informs the code to be bold. (I prefer 1 to 0 because it pops more.)
34 is the actual color code. It chooses blue.
48m is the background color. 48m is the same shade as the console window, so it seems there is no background.
To check for assignability, you can use the Type.IsAssignableFrom
method:
typeof(SomeType).IsAssignableFrom(typeof(Derived))
This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.
To check for strict inheritance, you can use Type.IsSubclassOf
:
typeof(Derived).IsSubclassOf(typeof(SomeType))
Add FormsModule
in Imports Array.
i.e
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
Or this can be done without using [(ngModel)]
by using
<input [value]='hero.name' (input)='hero.name=$event.target.value' placeholder="name">
instead of
<input [(ngModel)]="hero.name" placeholder="Name">
I use the FileSync plugin for Eclipse so I can live debug on Tomcat & I received NoClassFoundError
because I had added a sync entry for the bin
directory in the Eclipse workspace => classes
in the metadata
for Tomcat but hadn't also added a folder sync for the extlib
directory in Eclipse =>
C:\Users\Stuart\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\myApp\WEB-INF\lib
IE8 defaults to standards mode for the intERnet and quirks mode for the intRAnet. The HTML meta tag is ignored if you have the doctype set to xhtml transitional. The solution is to add an HTTP header in code. This worked for us. Now our intranet site is forcing IE8 to render the app in standards mode.
Added to PageInit of the base page class (ASP.net C#):
Response.AddHeader("X-UA-Compatible", "IE=EmulateIE8");
reference: http://ilia.ws/archives/196-IE8-X-UA-Compatible-Rant.html
You won't be able to make an ajax call to http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
from a file deployed at http://run.jsbin.com
due to the same-origin policy.
As the source (aka origin) page and the target URL are at different domains (run.jsbin.com
and www.ecb.europa.eu
), your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET
.
In a few words, the same-origin policy says that browsers should only allow ajax calls to services at the same domain of the HTML page.
A page at http://www.example.com/myPage.html
can only directly request services that are at http://www.example.com
, like http://www.example.com/api/myService
. If the service is hosted at another domain (say http://www.ok.com/api/myService
), the browser won't make the call directly (as you'd expect). Instead, it will try to make a CORS request.
To put it shortly, to perform a (CORS) request* across different domains, your browser:
Origin
header in the original request (with the page's domain as value) and perform it as usual; and thenAccess-Control-Allow-Origin
is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
* The above depicts the steps in a simple request, such as a regular GET
with no fancy headers. If the request is not simple (like a POST
with application/json
as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS
request to the target URL. Like above, it only will continue if the response to this OPTIONS
request contains the CORS headers. This OPTIONS
call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers
header.
Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at www.example.com
it will only make regular calls to www.example.com
! Other URLs, such as api.example.com
or even example.com
or www.example.com:8080
are considered different domains by the browser! Yes, if the port is different, then it is a different domain!
Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin
) to the server's responses. (Each server/language has a way to do that - check some solutions here.)
Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.
Using Spring for Android with RestTemplate https://spring.io/guides/gs/consuming-rest-android/
// The connection URL
String url = "https://ajax.googleapis.com/ajax/" +
"services/search/web?v=1.0&q={query}";
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url, String.class, "Android");
You could override the framework CSS (I guess you're using one) and set the size as you want, like this:
.pnx-msg-icon pnx-icon-msg-warning {
width: 24px !important;
height: 24px !important;
}
The "!important" property will make sure your code has priority to the framework's code. Make sure you are overriding the correct property, I don't know how the framework is working, this is just an example of !important usage.
$sql="SELECT * FROM TABLE_NAME WHERE item_id=".$item_id;
$query=mysql_query($sql);
while($myrow=mysql_fetch_array($query)) {
echo print_r($myrow,1);
}
The sp_xml_preparedocument
stored procedure will parse the XML and the OPENXML
rowset provider will show you a relational view of the XML data.
For details and more examples check the OPENXML documentation.
As for your question,
DECLARE @XML XML
SET @XML = '<rows><row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row></rows>'
DECLARE @handle INT
DECLARE @PrepareXmlStatus INT
EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML
SELECT *
FROM OPENXML(@handle, '/rows/row', 2)
WITH (
IdInvernadero INT,
IdProducto INT,
IdCaracteristica1 INT,
IdCaracteristica2 INT,
Cantidad INT,
Folio INT
)
EXEC sp_xml_removedocument @handle
From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning
the following
Excessive GC Time and OutOfMemoryError
The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.
The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).
in conjunction with a passage further down
One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,
java -Dsun.rmi.dgc.client.gcInterval=3600000
-Dsun.rmi.dgc.server.gcInterval=3600000
specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.
Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.
Of course, other interpretations are possible.
The correct way to use max in the having clause is by performing a self join first:
select t1.a, t1.b, t1.c
from table1 t1
join table1 t1_max
on t1.id = t1_max.id
group by t1.a, t1.b, t1.c
having t1.date = max(t1_max.date)
The following is how you would join with a subquery:
select t1.a, t1.b, t1.c
from table1 t1
where t1.date = (select max(t1_max.date)
from table1 t1_max
where t1.id = t1_max.id)
Be sure to create a single dataset before using an aggregate when dealing with a multi-table join:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
join #dataset d_max
on d.id = d_max.id
having d.date = max(d_max.date)
group by a, b, c
Sub query version:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
where d.date = (select max(d_max.date)
from #dataset d_max
where d.id = d_max.id)
Looks like @mixin
and @include
are not needed for a simple case like this.
One can just do:
.myclass {
font-weight: bold;
font-size: 90px;
}
.myotherclass {
@extend .myclass;
color: #000000;
}
First off, when you create a "bare repository", you're not going to be doing any work with it (it doesn't contain a working copy, so the git branch
command is not useful).
Now, the reason you wouldn't have a master
branch even after doing a git init
is that there are no commits: when you create your first commit, you will then have a master
branch.
This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.
The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.
Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)
The previous answers have covered the traditional menu used in android. Their is another option you can use if you are looking for an alternative
https://github.com/AnshulBansal/Android-Pulley-Menu
Pulley menu is an alternate to the traditional Menu which allows user to select any option for an activity intuitively. The menu is revealed by dragging the screen downwards and in that gesture user can also select any of the options.
another workaround:
var myarray = [];
$("#test").click(function() {
myarray[index]=$("#drop").val();
alert(myarray);
});
i wanted to add all checked checkbox to array. so example, if .each is used:
var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
if (this.checked) {
var p=$('.pp').eq(idx).val();
vpp[incr]=(p);
incr++;
}
});
//do what ever with vpp array;
They are all wrong I just wrote this in about 10 seconds. With this I managed to just call the object.getQuestion("linenumber") in the main method to return whatever line I want.
public class Questions {
File file = new File("Question2Files/triviagame1.txt");
public Questions() {
}
public String getQuestion(int numLine) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
for(int i = 0; i < numLine; i++) {
line = br.readLine();
}
return line; }}
No need to go in such deep technicalities, and get yourself blasted. Let me explain it in the most easiest way. We all have studied "Sets" during our school-age in Mathematics. Just consider 3D numpy array as the formation of "sets".
x = np.zeros((2,3,4))
Simply Means:
2 Sets, 3 Rows per Set, 4 Columns
Example:
Input
x = np.zeros((2,3,4))
Output
Set # 1 ---- [[[ 0., 0., 0., 0.], ---- Row 1
[ 0., 0., 0., 0.], ---- Row 2
[ 0., 0., 0., 0.]], ---- Row 3
Set # 2 ---- [[ 0., 0., 0., 0.], ---- Row 1
[ 0., 0., 0., 0.], ---- Row 2
[ 0., 0., 0., 0.]]] ---- Row 3
Explanation: See? we have 2 Sets, 3 Rows per Set, and 4 Columns.
Note: Whenever you see a "Set of numbers" closed in double brackets from both ends. Consider it as a "set". And 3D and 3D+ arrays are always built on these "sets".
Yes;
git commit FILE
will commit just FILE. Then you can use
git reset --hard
to undo local changes in other files.
There may be other ways too that I don't know about...
edit: or, as NicDumZ said, git-checkout just the files you want to undo the changes on (the best solution depends on wether there are more files to commit or more files to undo :-)
After trying many things with no success, I've managed to get SSH access to the server, and import my 80Mb database with a command line, instead of phpMyAdmin. Here is the command:
mysql -u root -p -D mydatabase -o < mydatabase.sql
It's much easier to import big databases, if you are running xammp on windows, the path for mysql.exe is C:\xampp\mysql\bin\mysql.exe
The newest, most recent, up to date answer
This post is really old (it's 7 years old when I answered it), so no one of the other answers used the new and recommended way, which is HttpClient
class.
HttpClient
is considered the new API and it should replace the old ones (WebClient
and WebRequest
)
string url = "page url";
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
string result = content.ReadAsStringAsync().Result;
}
}
for more information about how to use the HttpClient
class (especially in async cases), you can refer this question
NOTE 1: If you want to use async/await
string url = "page url";
HttpClient client = new HttpClient(); // actually only one object should be created by Application
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
}
}
NOTE 2: If use C# 8 features
string url = "page url";
HttpClient client = new HttpClient();
using HttpResponseMessage response = await client.GetAsync(url);
using HttpContent content = response.Content;
string result = await content.ReadAsStringAsync();
It doesn't work because Date - Date
relies on exactly the kind of type coercion TypeScript is designed to prevent.
There is a workaround this using the +
prefix:
var t = Date.now() - +(new Date("2013-02-20T12:01:04.753Z");
Or, if you prefer not to use Date.now()
:
var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));
Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()
You can brute force it like this:
Public Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
Dim i
For i = LBound(arr) To UBound(arr)
If arr(i) = stringToBeFound Then
IsInArray = True
Exit Function
End If
Next i
IsInArray = False
End Function
Use like
IsInArray("example", Array("example", "someother text", "more things", "and another"))
Or add "sort name" to list alphabetically
Get-ADPrincipalGroupMembership username | select name | sort name
Try adding the profile
attribute to your head
tag and use "image/x-icon"
for the type
attribute:
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">
If the above code doesn't work, try using the full icon path for the href
attribute:
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">
It would help if you provided the error you are seeing. Look at http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html and you will see that max only returns the max between two numbers, so likely you code is not even compiling.
Solve all your compilation errors first.
Then your homework will consist of finding the max of three numbers by comparing the first two together, and comparing that max result with the third value. You should have enough to find your answer now.
As of C++20, yes.
As of C++17, you can use string_view
:
constexpr std::string_view sv = "hello, world";
A string_view
is a string
-like object that acts as an immutable, non-owning reference to any sequence of char
objects.
Thank you for this thread. I've been having a hard time implementing a Timer in my code for 5 minutes to run an activity, because my phone I have set to screen off/sleep around 2 minutes. With the above information it appears I have been able to get the work around.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Time Lockout after 5 mins */
getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
Intent i = new Intent(AccountsList.this, AppEntryActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
return;
}
}, 300000);
/* Time Lockout END */
}
the return statement exits from the current function and exit() exits from the program
they are the same when used in main() function
also return is a statement while exit() is a function which requires stdlb.h header file
On macOS Sierra, creating ~/.mailrc with smtp setup did the trick:
set smtp-use-starttls
set smtp=smtp://smtp.gmail.com:587
set smtp-auth=login
set [email protected]
set smtp-auth-password=yourpass
Then to send mail from CLI:
echo "your message" | mail -s "your subject" [email protected]
with opencv 4.0;
-DOPENCV_GENERATE_PKGCONFIG=ON
to build argumentspkg-config --cflags --libs opencv4
instead of opencvI found out the hard way that if your listbox items are assigned via a data source
List<String> workTables = hhsdbutils.GetWorkTableNames();
listBoxWork.DataSource = workTables;
...you have to unbind that before doing the removal:
listBoxWork.DataSource = null;
for (int i = listBoxWork.Items.Count - 1; i >= 0; --i)
{
if (listBoxWork.Items[i].ToString().Contains(listboxVal))
{
listBoxWork.Items.RemoveAt(i);
}
}
Without the "listBoxWork.DataSource = null;
" line, I was getting, "Value does not fall within the expected range"
You can do like
$timeout(function() {
angular.element('#btn2').triggerHandler('click');
});
GET CURRENT UTC TIME IN REQUIRED FORMAT
// Current UTC time
OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);
// GET LocalDateTime
LocalDateTime localDateTime = utc.toLocalDateTime();
System.out.println("*************" + localDateTime);
// formated UTC time
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(" formats as " + dTF.format(localDateTime));
//GET UTC time for current date
Date now= new Date();
LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));
LATERAL
join?The feature was introduced with PostgreSQL 9.3.
Quoting the manual:
Subqueries appearing in
FROM
can be preceded by the key wordLATERAL
. This allows them to reference columns provided by precedingFROM
items. (WithoutLATERAL
, each subquery is evaluated independently and so cannot cross-reference any otherFROM
item.)Table functions appearing in
FROM
can also be preceded by the key wordLATERAL
, but for functions the key word is optional; the function's arguments can contain references to columns provided by precedingFROM
items in any case.
Basic code examples are given there.
A LATERAL
join is more like a correlated subquery, not a plain subquery, in that expressions to the right of a LATERAL
join are evaluated once for each row left of it - just like a correlated subquery - while a plain subquery (table expression) is evaluated once only. (The query planner has ways to optimize performance for either, though.)
Related answer with code examples for both side by side, solving the same problem:
For returning more than one column, a LATERAL
join is typically simpler, cleaner and faster.
Also, remember that the equivalent of a correlated subquery is LEFT JOIN LATERAL ... ON true
:
There are things that a LATERAL
join can do, but a (correlated) subquery cannot (easily). A correlated subquery can only return a single value, not multiple columns and not multiple rows - with the exception of bare function calls (which multiply result rows if they return multiple rows). But even certain set-returning functions are only allowed in the FROM
clause. Like unnest()
with multiple parameters in Postgres 9.4 or later. The manual:
This is only allowed in the
FROM
clause;
So this works, but cannot (easily) be replaced with a subquery:
CREATE TABLE tbl (a1 int[], a2 int[]);
SELECT * FROM tbl, unnest(a1, a2) u(elem1, elem2); -- implicit LATERAL
The comma (,
) in the FROM
clause is short notation for CROSS JOIN
.
LATERAL
is assumed automatically for table functions.
About the special case of UNNEST( array_expression [, ... ] )
:
SELECT
listYou can also use set-returning functions like unnest()
in the SELECT
list directly. This used to exhibit surprising behavior with more than one such function in the same SELECT
list up to Postgres 9.6. But it has finally been sanitized with Postgres 10 and is a valid alternative now (even if not standard SQL). See:
Building on above example:
SELECT *, unnest(a1) AS elem1, unnest(a2) AS elem2
FROM tbl;
Comparison:
dbfiddle for pg 9.6 here
dbfiddle for pg 10 here
For the
INNER
andOUTER
join types, a join condition must be specified, namely exactly one ofNATURAL
,ON
join_condition, orUSING
(join_column [, ...]). See below for the meaning.
ForCROSS JOIN
, none of these clauses can appear.
So these two queries are valid (even if not particularly useful):
SELECT *
FROM tbl t
LEFT JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t ON TRUE;
SELECT *
FROM tbl t, LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;
While this one is not:
SELECT *
FROM tbl t
LEFT JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;
That's why Andomar's code example is correct (the CROSS JOIN
does not require a join condition) and Attila's is was not.
String clsName = "Ex"; // use fully qualified name
Class cls = Class.forName(clsName);
Object clsInstance = (Object) cls.newInstance();
Check the Java Tutorial trail on Reflection at http://java.sun.com/docs/books/tutorial/reflect/TOC.html for further details.
Observer-Observable: it is used in ApplicationContext's event mechanism
Why dont you try and write a Stored Procedure
for this?
You can get the Result Set
out and in the same Stored Procedure
you can Insert
what you want.
The only thing is you might not get the newly inserted rows in the Result Set
if you Insert
after the Select
.
Javascript will be required; for example:
$(function(){
$('[type="date"]').prop('max', function(){
return new Date().toJSON().split('T')[0];
});
});
In Chrome, you are supposed to be able to allow this capability with a runtime flag --allow-file-access-from-files
However, it looks like there is a problem with current versions of Chrome (37, 38) where this doesn't work unless you also pass the runtime flag --disable-web-security
That's an unacceptable solution, except perhaps as a short-term workaround, but it has been identified as an issue: https://code.google.com/p/chromium/issues/detail?id=379206
A submodule is its own repo/work-area, with its own .git
directory.
So, first commit/push
your submodule's changes:
$ cd path/to/submodule
$ git add <stuff>
$ git commit -m "comment"
$ git push
Then, update your main project to track the updated version of the submodule:
$ cd /main/project
$ git add path/to/submodule
$ git commit -m "updated my submodule"
$ git push
You could also use vbCrLf
which corresponds to Chr(13)
& Chr(10)
.
In C int foo()
and int foo(void)
are different functions. int foo()
accepts an arbitrary number of arguments, while int foo(void)
accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void
consistently when you mean no arguments.
If you have a variable a
, extern int a;
is a way to tell the compiler that a
is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (extern
, static
) only affects its visibility and extern
is the default, so extern
is actually unnecessary.
I suggest removing the extern
, it is extraneous and is usually omitted.
I had trouble getting selectable to work with ASP.NET. It turns out I wasn't properly including everything, but this gentleman made it foolproof: Three steps to use jQuery UI in ASP.NET MVC 5.
You may be able to approximate the size by pretending to serializing it with a binary serializer (but routing the output to oblivion) if you're working with serializable objects.
class Program
{
static void Main(string[] args)
{
A parent;
parent = new A(1, "Mike");
parent.AddChild("Greg");
parent.AddChild("Peter");
parent.AddChild("Bobby");
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
SerializationSizer ss = new SerializationSizer();
bf.Serialize(ss, parent);
Console.WriteLine("Size of serialized object is {0}", ss.Length);
}
}
[Serializable()]
class A
{
int id;
string name;
List<B> children;
public A(int id, string name)
{
this.id = id;
this.name = name;
children = new List<B>();
}
public B AddChild(string name)
{
B newItem = new B(this, name);
children.Add(newItem);
return newItem;
}
}
[Serializable()]
class B
{
A parent;
string name;
public B(A parent, string name)
{
this.parent = parent;
this.name = name;
}
}
class SerializationSizer : System.IO.Stream
{
private int totalSize;
public override void Write(byte[] buffer, int offset, int count)
{
this.totalSize += count;
}
public override bool CanRead
{
get { return false; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override void Flush()
{
// Nothing to do
}
public override long Length
{
get { return totalSize; }
}
public override long Position
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
}
Datatable.clear()
method from class DataTable
There is a Hidden
helper alongside HiddenFor
which lets you set the value.
@Html.Hidden("RequiredProperty", "default")
EDIT Based on the edit you've made to the question, you could do this, but I believe you're moving into territory where it will be cheaper and more effective, in the long run, to fight for making the code change. As has been said, even by yourself, the controller or view model should be setting the default.
This code:
<ul>
@{
var stacks = new System.Diagnostics.StackTrace().GetFrames();
foreach (var frame in stacks)
{
<li>@frame.GetMethod().Name - @frame.GetMethod().DeclaringType</li>
}
}
</ul>
Will give output like this:
Execute - ASP._Page_Views_ViewDirectoryX__SubView_cshtml
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
ExecutePageHierarchy - System.Web.Mvc.WebViewPage
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
RenderView - System.Web.Mvc.RazorView
Render - System.Web.Mvc.BuildManagerCompiledView
RenderPartialInternal - System.Web.Mvc.HtmlHelper
RenderPartial - System.Web.Mvc.Html.RenderPartialExtensions
Execute - ASP._Page_Views_ViewDirectoryY__MainView_cshtml
So assuming the MVC framework will always go through the same stack, you can grab var frame = stacks[8];
and use the declaring type to determine who your parent view is, and then use that determination to set (or not) the default value. You could also walk the stack instead of directly grabbing [8]
which would be safer but even less efficient.
If you are using microsoft query, you can add "?" to your query...
select name from user where id= ?
that will popup a small window asking for the cell/data/etc when you go back to excel.
In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.
configure static ip on the raspberry pi:
sudo nano /etc/network/interfaces
and then add:
iface eth0 inet static
address 169.254.0.2
netmask 255.255.255.0
broadcast 169.254.0.255
then you can acces your raspberry via ssh
ssh [email protected]
They are useful to identify each elements in SQL.
For example:
CREATE TABLE SchemaName.TableName (
This would actually create a table by the name SchemaName.TableName
under default dbo
schema even though the intention might be to create the table inside the SchemaName
schema.
The correct way would be the following:
CREATE TABLE [SchemaName].[TableName] (
Now it it knows what is the table name and in which schema should it be created in (rightly in the SchemaName
schema and not in the default dbo
schema)
I use this code modifying others that I saw. Only grand to the user write if the key pressed or pasted text pass the pattern test (match) (this example is a text input that only allows 8 digits)
$("input").on("keypress paste", function(e){
var c = this.selectionStart, v = $(this).val();
if (e.type == "keypress")
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode)
else
var key = e.originalEvent.clipboardData.getData('Text')
var val = v.substr(0, c) + key + v.substr(c, v.length)
if (!val.match(/\d{0,8}/) || val.match(/\d{0,8}/).toString() != val) {
e.preventDefault()
return false
}
})
Have you tried using Project > Clean... from the menu? This will force a new build on the selected projects in Eclipse.
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
driver = new ChromeDriver(options);
I have used it for Java with Chrome browser it is working nice
You can use select2 plugin for creating such a filter. With this lot's of coding work can be avoided. You can grab the plugin from https://select2.github.io/
This plugin is much simple to apply and even advanced work can be easily done with it. :)
char *p = "String"; means pointer to a string type variable.
char p3[5] = "String"
; means you are pre-defining the size of the array to consist of no more than 5 elements. Note that,for strings the null "\0" is also considered as an element.So,this statement would give an error since the number of elements is 7 so it should be:
char p3[7]= "String";
There is another way, take this as example
Dim sr As String
sr = "6:10"
Rows(sr).Select
All you need to do is to convert your variables iStartRow
, iEndRow
to a string.
To convert a generic list to data table, you could use the DataTableGenerator
This library lets you convert your list into a data table with multi-feature like
Window -> Preferences -> Java -> Editor -> content assist > enter
".abcdefghijklmnopqrstuvwxyz"
in the Auto activation triggers.
It will allow you to complete your code.
You can use the Date
property of the DateTime object - eg
DateTime midnight = DateTime.Now.Date;
So your code example becomes
private DateTime _Begin = DateTime.Now.Date;
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }
PS. going back to your original code setting the hours to 12 will give you time of noon for the current day, so instead you could have used 0...
var now = DateTime.Now;
new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
This will capture requests for files like version
,
release
, and README.md
, etc. which should be
treated either as endpoints, if defined (as in the
case of /release), or as "not found."
Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.
Sometimes it may happen that there are multiple schema created in a database.
So to be specific schema we need to target, so this will help to do it.
SELECT count(*) into @colCnt FROM information_schema.columns WHERE table_name = 'mytable' AND column_name = 'mycolumn' and table_schema = DATABASE();
IF @colCnt = 0 THEN
ALTER TABLE `mytable` ADD COLUMN `mycolumn` VARCHAR(20) DEFAULT NULL;
END IF;
TLDR: Compress and embed your entire css script between your <style></style>
tags.
I've been chasing down that elusive 100/100 score for about a week now. Like you, the last remaining item was was eliminating "render-blocking css for above the fold content."
Surely there is an easy solve?? Nope. I tried out Filament group's loadCSS solution. Too much .js for my liking.
What about async
attributes for css (like js)? They don't exist.
I was ready to give up. Then it dawned on me. If linking the script was blocking the render, what if I instead embedded my entire css in the head instead. That way there was nothing to block.
It seemed absolutely WRONG to embed 1263 lines of CSS in my style tag. But I gave it a whirl. I compressed it (and prefixed it) first using:
postcss -u autoprefixer --autoprefixer.browsers 'last 2 versions' -u cssnano --cssnano.autoprefixer false *.css -d min/
See the NPM postcss package.
Now it was just one LONG line of space-less css. I plopped the css in <style>your;great-wall-of-china-long;css;here</style>
tags on my home page. Then I re-analyzed with page speed insights.
I went from 90/100 to 99/100 on mobile!!!
This goes against everything in me (and probably you). But it SOLVED the problem. I'm just using it on my home page for now and including the compressed css programmatically via a PHP include.
YMMV (your mileage may vary) pending on the length of your css. Google may ding you for too much above the fold content. But don't assume; test!
I'm only doing this on my home page for now so people get a FAST render on my most important page.
Your css won't get cached. I'm not too worried though. The second they hit another page on my site, the .css will get cached (see Note 1).
When "waiting for lock on repository", delete the repository file: .hg/wlock
(or it may be in
).hg/store/lock
When deleting the lock file, you must make sure nothing else is accessing the repository. (If the lock is a string of zeros or blank, this is almost certainly true).
position: fixed;
will solve your issue. As an example, review my implementation of a fixed message area overlay (populated programmatically):
#mess {
position: fixed;
background-color: black;
top: 20px;
right: 50px;
height: 10px;
width: 600px;
z-index: 1000;
}
And in the HTML
<body>
<div id="mess"></div>
<div id="data">
Much content goes here.
</div>
</body>
When #data
becomes longer tha the sceen, #mess
keeps its position on the screen, while #data
scrolls under it.
Do not hesitate to put constraints on the database. You'll be sure to have a consistent database, and that's one of the good reasons to use a database. Especially if you have several applications requesting it (or just one application but with a direct mode and a batch mode using different sources).
With MySQL you do not have advanced constraints like you would have in postgreSQL but at least the foreign key constraints are quite advanced.
We'll take an example, a company table with a user table containing people from theses company
CREATE TABLE COMPANY (
company_id INT NOT NULL,
company_name VARCHAR(50),
PRIMARY KEY (company_id)
) ENGINE=INNODB;
CREATE TABLE USER (
user_id INT,
user_name VARCHAR(50),
company_id INT,
INDEX company_id_idx (company_id),
FOREIGN KEY (company_id) REFERENCES COMPANY (company_id) ON...
) ENGINE=INNODB;
Let's look at the ON UPDATE clause:
And now on the ON DELETE side:
usually my default is: ON DELETE RESTRICT ON UPDATE CASCADE. with some ON DELETE CASCADE
for track tables (logs--not all logs--, things like that) and ON DELETE SET NULL
when the master table is a 'simple attribute' for the table containing the foreign key, like a JOB table for the USER table.
Edit
It's been a long time since I wrote that. Now I think I should add one important warning. MySQL has one big documented limitation with cascades. Cascades are not firing triggers. So if you were over confident enough in that engine to use triggers you should avoid cascades constraints.
MySQL triggers activate only for changes made to tables by SQL statements. They do not activate for changes in views, nor by changes to tables made by APIs that do not transmit SQL statements to the MySQL Server
==> See below the last edit, things are moving on this domain
Triggers are not activated by foreign key actions.
And I do not think this will get fixed one day. Foreign key constraints are managed by the InnoDb storage and Triggers are managed by the MySQL SQL engine. Both are separated. Innodb is the only storage with constraint management, maybe they'll add triggers directly in the storage engine one day, maybe not.
But I have my own opinion on which element you should choose between the poor trigger implementation and the very useful foreign keys constraints support. And once you'll get used to database consistency you'll love PostgreSQL.
as stated by @IstiaqueAhmed in the comments, the situation has changed on this subject. So follow the link and check the real up-to-date situation (which may change again in the future).
from os import listdir
def find_csv_filenames( path_to_dir, suffix=".csv" ):
filenames = listdir(path_to_dir)
return [ filename for filename in filenames if filename.endswith( suffix ) ]
The function find_csv_filenames()
returns a list of filenames as strings, that reside in the directory path_to_dir
with the given suffix (by default, ".csv").
Addendum
How to print the filenames:
filenames = find_csv_filenames("my/directory")
for name in filenames:
print name
The best response to this question is to use margin-auto
but for using it you must know the width
of your div
in px
or %
.
CSS code:
div{
width:30%;
margin-left:auto;
margin-right:auto;
}
Addressing the first question, if you need to take several rows grouped by certain criteria with the other column with max value you can do something like this:
var query =
from u1 in table
join u2 in (
from u in table
group u by u.GroupId into g
select new { GroupId = g.Key, MaxStatus = g.Max(x => x.Status) }
) on new { u1.GroupId, u1.Status } equals new { u2.GroupId, Status = u2.MaxStatus}
select u1;
// Using LINQ and just referencing p.Employer will lazy load
// I am not at a computer but I know I have lazy loaded in one
// query with a single query call like below.
List<Person> persons = new List<Person>();
using(MyDbContext dbContext = new MyDbContext())
{
persons = (
from p in dbcontext.Persons
select new Person{
Name = p.Name,
Email = p.Email,
Employer = p.Employer
}).ToList();
}
Try This:
(SELECT p.LastName, p.FirstName, o.OrderNo
FROM Persons p
LEFT JOIN Orders o
ON o.OrderNo = p.P_id
)
UNION
(SELECT p.LastName, p.FirstName, o.OrderNo
FROM Persons p
RIGHT JOIN Orders o
ON o.OrderNo = p.P_id
);
+----------+-----------+---------+
| LastName | FirstName | OrderNo |
+----------+-----------+---------+
| Singh | Shashi | 1 |
| Yadav | Sunil | NULL |
| Singh | Satya | NULL |
| Jain | Ankit | NULL |
| NULL | NULL | 11 |
| NULL | NULL | 12 |
| NULL | NULL | 13 |
+----------+-----------+---------+
Elaborating to the answer of @Cephalopod, if you wanted all column names in a list you could use this oneliner:
List<String> columns =
Arrays.asList(MyClass.class.getFields())
.stream()
.filter(f -> f.getAnnotation(Column.class)!=null)
.map(f -> f.getAnnotation(Column.class).columnName())
.collect(Collectors.toList());
It's a linker error. ld
is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.
The error message tells you that none of the object files you're linking against contains a definition for avergecolumns
. The reason for that is that the function you've defined is called averagecolumns
(in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).
hi firstly there seems to be many 'errors' in your html where you are missing closing tags, you could try wrapping the contents of your <body>
in a fixed width <div style="margin: 0 auto; width: 900px>
to achieve what you have done with the body {margin: 0 10% 0 10%}
Replace the whitespace characters, and then convert it(using the intval function or by regular typecasting)
intval(str_replace(" ", "", $b))
points_small = dict(filter(lambda (a,(b,c)): b<5 and c < 5, points.items()))
Now the class is this
<img src="img/img5.jpg" width="200px" class="rounded-circle float-right">
_x000D_
Yes you can define static member functions in *.cpp file. If you define it in the header, compiler will by default treat it as inline. However, it does not mean separate copies of the static member function will exist in the executable. Please follow this post to learn more about this: Are static member functions in c++ copied in multiple translation units?
I've modified your plunker to get it working via angular-xeditable:
http://plnkr.co/edit/xUDrOS?p=preview
It is common solution for inline editing - you creale hyperlinks with editable-text
directive
that toggles into <input type="text">
tag:
<a href="#" editable-text="bday.name" ng-click="myform.$show()" e-placeholder="Name">
{{bday.name || 'empty'}}
</a>
For date I used editable-date
directive that toggles into html5 <input type="date">
.
we can change Content-type like this in $.post
$.post(url,data, function (data, status, xhr) { xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");});
Found that setting the secure property in Session_Start is sufficient, as recommended in MSDN blog "Securing Session ID: ASP/ASP.NET" with some augmentation.
protected void Session_Start(Object sender, EventArgs e)
{
SessionStateSection sessionState =
(SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
string sidCookieName = sessionState.CookieName;
if (Request.Cookies[sidCookieName] != null)
{
HttpCookie sidCookie = Response.Cookies[sidCookieName];
sidCookie.Value = Session.SessionID;
sidCookie.HttpOnly = true;
sidCookie.Secure = true;
sidCookie.Path = "/";
}
}
As requested, I decided to extend my comment on forefinger's answer to a full-fledged answer. Although his answer is correct, it is needlessly complex. Furthermore all current answers use signed int
s to represent the values. This is dangerous, as right-shifting of negative values is implementation-defined (i.e. not portable) and left-shifting can lead to undefined behavior (see this question).
By right-shifting the desired bit into the least significant bit position, masking can be done with 1
. No need to compute a new mask value for each bit.
(n >> k) & 1
As a complete program, computing (and subsequently printing) an array of single bit values:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
unsigned
input = 0b0111u,
n_bits = 4u,
*bits = (unsigned*)malloc(sizeof(unsigned) * n_bits),
bit = 0;
for(bit = 0; bit < n_bits; ++bit)
bits[bit] = (input >> bit) & 1;
for(bit = n_bits; bit--;)
printf("%u", bits[bit]);
printf("\n");
free(bits);
}
Assuming that you want to calculate all bits as in this case, and not a specific one, the loop can be further changed to
for(bit = 0; bit < n_bits; ++bit, input >>= 1)
bits[bit] = input & 1;
This modifies input
in place and thereby allows the use of a constant width, single-bit shift, which may be more efficient on some architectures.
In my component I need access to window.location.search
. This is what I did in the Jest test:
Object.defineProperty(global, "window", {
value: {
location: {
search: "test"
}
}
});
In case window properties must be different in different tests, we can put window mocking into a function, and make it writable in order to override for different tests:
function mockWindow(search, pathname) {
Object.defineProperty(global, "window", {
value: {
location: {
search,
pathname
}
},
writable: true
});
}
And reset after each test:
afterEach(() => {
delete global.window.location;
});
less typing way:
func fprint(format: String, _ args: CVarArgType...) {
print(NSString(format: format, arguments: getVaList(args)))
}
Since Java 9, it is possible to use Map.of(...)
, like so:
Map<String, Integer> immutableMap = Map.of("One", 1,
"Two", 2,
"Three", 3);
This map is immutable. If you want the map to be mutable, you have to add:
Map<String, Integer> hashMap = new HashMap<>(immutableMap);
If you can't use Java 9, you're stuck with writing a similar helper method yourself or using a third-party library (like Guava) to add that functionality for you.
One thing to do is swap cables. I was using one that was only capable of charging!
=Replace(Format(CDate(Now()),"MM.dd.yyyy"), ".", "/")
Try the out-of-the-box solution (ASP.NET MVC 4 or later):
@{
var bundle = BundleTable.Bundles.GetRegisteredBundles().First(b => b.Path == "~/js");
bundle.Include("~/Scripts/myFile.js");
}
Use ClassLoader#getResource()
instead if its URI represents a valid local disk file system path.
URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...
If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.
Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...
That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream
instead of InputStream
. If you can, just fix the API to ask for an InputStream
instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.
A = [1,2,3,4]
B = [2,5]
#A - B
x = list(set(A) - set(B))
#B - A
y = list(set(B) - set(A))
print x
print y