For me, none of the solutions work. I had to download the XCode from the App store. It's too big around 12 GB. After installing it works like a charm.
You define var scatterSeries = [];
, and then try to parse it as a json string at console.info(JSON.parse(scatterSeries));
which obviously fails. The variable is converted to an empty string, which causes an "unexpected end of input" error when trying to parse it.
Return ABDeadlineType
from repository:
public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
List<ABDeadlineType> findAllSummarizedBy();
}
and then convert to DeadlineType. Manually or use mapstruct.
Or call constructor from @Query
annotation:
public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
@Query("select new package.DeadlineType(a.id, a.code) from ABDeadlineType a ")
List<DeadlineType> findAllSummarizedBy();
}
Or use @Projection
:
@Projection(name = "deadline", types = { ABDeadlineType.class })
public interface DeadlineType {
@Value("#{target.id}")
String getId();
@Value("#{target.code}")
String getText();
}
Update:
Spring can work without @Projection
annotation:
public interface DeadlineType {
String getId();
String getText();
}
You shouldn't use ${varName}
when you're outside of strings, you should just use varName
. Inside strings you use it like this; echo "this is a string ${someVariable}";
. Infact you can place an general java expression inside of ${...}
; echo "this is a string ${func(arg1, arg2)}
.
If your chart uses both fill
and color
aesthetics, you can remove the legend with:
+ guides(fill=FALSE, color=FALSE)
You could use lsof
to see what application is listening on port 80:
sudo lsof -i TCP:80
Whenever you encounter an error with this message use my_string.encode()
.
(where my_string
is the string you're passing to a function/method).
The encode
method of str
objects returns the encoded version of the string as a bytes
object which you can then use.
In this specific instance, socket methods such as .send
expect a bytes object as the data to be sent, not a string object.
Since you have an object of type str
and you're passing it to a function/method that expects an object of type bytes
, an error is raised that clearly explains that:
TypeError: a bytes-like object is required, not 'str'
So the encode
method of strings is needed, applied on a str
value and returning a bytes
value:
>>> s = "Hello world"
>>> print(type(s))
<class 'str'>
>>> byte_s = s.encode()
>>> print(type(byte_s))
<class 'bytes'>
>>> print(byte_s)
b"Hello world"
Here the prefix b
in b'Hello world'
denotes that this is indeed a bytes object. You can then pass it to whatever function is expecting it in order for it to run smoothly.
If you have issues with the xcode-select --install
command; e.g. I kept getting a network problem timeout, then try downloading the dmg at developer.apple.com/downloads (Command line tools OS X 10.11) for Xcode 7.1
First, array_length
should be an integer and not a string:
array_length = len(array_dates)
Second, your for
loop should be constructed using range
:
for i in range(array_length): # Use `xrange` for python 2.
Third, i
will increment automatically, so delete the following line:
i += 1
Note, one could also just zip
the two lists given that they have the same length:
import csv
dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']
csv_file_patch = '/path/to/filename.csv'
with open(csv_file_patch, 'w') as fout:
csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
result_array = zip(dates, urls)
csv_file.writerows(result_array)
I was having the problem as a beginner..........
There was issue in the path of the xml file I have saved.
Example (with complete source code) to read a json configuration file:
https://github.com/sksodhi/CodeNuggets/tree/master/json/config_read
> pwd
/root/CodeNuggets/json/config_read
> ls
Makefile README.md ReadJsonCfg.cpp cfg.json
> cat cfg.json
{
"Note" : "This is a cofiguration file",
"Config" : {
"server-ip" : "10.10.10.20",
"server-port" : "5555",
"buffer-length" : 5000
}
}
> cat ReadJsonCfg.cpp
#include <iostream>
#include <json/value.h>
#include <jsoncpp/json/json.h>
#include <fstream>
void
displayCfg(const Json::Value &cfg_root);
int
main()
{
Json::Reader reader;
Json::Value cfg_root;
std::ifstream cfgfile("cfg.json");
cfgfile >> cfg_root;
std::cout << "______ cfg_root : start ______" << std::endl;
std::cout << cfg_root << std::endl;
std::cout << "______ cfg_root : end ________" << std::endl;
displayCfg(cfg_root);
}
void
displayCfg(const Json::Value &cfg_root)
{
std::string serverIP = cfg_root["Config"]["server-ip"].asString();
std::string serverPort = cfg_root["Config"]["server-port"].asString();
unsigned int bufferLen = cfg_root["Config"]["buffer-length"].asUInt();
std::cout << "______ Configuration ______" << std::endl;
std::cout << "server-ip :" << serverIP << std::endl;
std::cout << "server-port :" << serverPort << std::endl;
std::cout << "buffer-length :" << bufferLen<< std::endl;
}
> cat Makefile
CXX = g++
PROG = readjsoncfg
CXXFLAGS += -g -O0 -std=c++11
CPPFLAGS += \
-I. \
-I/usr/include/jsoncpp
LDLIBS = \
-ljsoncpp
LDFLAGS += -L/usr/local/lib $(LDLIBS)
all: $(PROG)
@echo $(PROG) compilation success!
SRCS = \
ReadJsonCfg.cpp
OBJS=$(subst .cc,.o, $(subst .cpp,.o, $(SRCS)))
$(PROG): $(OBJS)
$(CXX) $^ $(LDFLAGS) -o $@
clean:
rm -f $(OBJS) $(PROG) ./.depend
depend: .depend
.depend: $(SRCS)
rm -f ./.depend
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -MM $^ > ./.depend;
include .depend
> make
Makefile:43: .depend: No such file or directory
rm -f ./.depend
g++ -g -O0 -std=c++11 -I. -I/usr/include/jsoncpp -MM ReadJsonCfg.cpp > ./.depend;
g++ -g -O0 -std=c++11 -I. -I/usr/include/jsoncpp -c -o ReadJsonCfg.o ReadJsonCfg.cpp
g++ ReadJsonCfg.o -L/usr/local/lib -ljsoncpp -o readjsoncfg
readjsoncfg compilation success!
> ./readjsoncfg
______ cfg_root : start ______
{
"Config" :
{
"buffer-length" : 5000,
"server-ip" : "10.10.10.20",
"server-port" : "5555"
},
"Note" : "This is a cofiguration file"
}
______ cfg_root : end ________
______ Configuration ______
server-ip :10.10.10.20
server-port :5555
buffer-length :5000
>
In version 3 of a Docker Compose file, you can use RESTART.
For example:
docker-compose.yml
worker:
build: myapp/.
volumes:
- myapp/.:/usr/src/app:ro
restart: on-failure
depends_on:
- rabbitmq
rabbitmq:
image: rabbitmq:3-management
Note that I used depends_on instead of links since the latter is deprecated in version 3.
Even though it works, it might not be the ideal solution since you restart the docker container at every failure.
Have a look to RESTART_POLICY as well. it let you fine tune the restart policy.
When you use Compose in production, it is actually best practice to use the restart policy :
Specifying a restart policy like restart: always to avoid downtime
For docker-compose
using bridge networking to create a private network between containers, the accepted solution using docker0
doesn't work because the egress interface from the containers is not docker0
, but instead, it's a randomly generated interface id, such as:
$ ifconfig
br-02d7f5ba5a51: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.32.1 netmask 255.255.240.0 broadcast 192.168.47.255
Unfortunately that random id is not predictable and will change each time compose has to recreate the network (e.g. on a host reboot). My solution to this is to create the private network in a known subnet and configure iptables
to accept that range:
Compose file snippet:
version: "3.7"
services:
mongodb:
image: mongo:4.2.2
networks:
- mynet
# rest of service config and other services removed for clarity
networks:
mynet:
name: mynet
ipam:
driver: default
config:
- subnet: "192.168.32.0/20"
You can change the subnet if your environment requires it. I arbitrarily selected 192.168.32.0/20
by using docker network inspect
to see what was being created by default.
Configure iptables
on the host to permit the private subnet as a source:
$ iptables -I INPUT 1 -s 192.168.32.0/20 -j ACCEPT
This is the simplest possible iptables
rule. You may wish to add other restrictions, for example by destination port. Don't forget to persist your iptables rules when you're happy they're working.
This approach has the advantage of being repeatable and therefore automatable. I use ansible's template
module to deploy my compose file with variable substitution and then use the iptables
and shell
modules to configure and persist the firewall rules, respectively.
@user1664035 & @Attila Mika's suggestion worked. You have to navigate to Control Panel -> Programs And Features -> Turn Windows Features On or Off. And refer to the screenshot. You should check IIS Management console.
Updated version of @martin's answer for Swift 5+ using Combine. This one also includes unavailibity reason check for iOS 14.
import Combine
import Network
enum NetworkType {
case wifi
case cellular
case loopBack
case wired
case other
}
final class ReachabilityService: ObservableObject {
@Published var reachabilityInfos: NWPath?
@Published var isNetworkAvailable: Bool?
@Published var typeOfCurrentConnection: NetworkType?
private let monitor = NWPathMonitor()
private let backgroundQueue = DispatchQueue.global(qos: .background)
init() {
setUp()
}
init(with interFaceType: NWInterface.InterfaceType) {
setUp()
}
deinit {
monitor.cancel()
}
}
private extension ReachabilityService {
func setUp() {
monitor.pathUpdateHandler = { [weak self] path in
self?.reachabilityInfos = path
switch path.status {
case .satisfied:
print("ReachabilityService: satisfied")
self?.isNetworkAvailable = true
break
case .unsatisfied:
print("ReachabilityService: unsatisfied")
if #available(iOS 14.2, *) {
switch path.unsatisfiedReason {
case .notAvailable:
print("ReachabilityService: unsatisfiedReason: notAvailable")
break
case .cellularDenied:
print("ReachabilityService: unsatisfiedReason: cellularDenied")
break
case .wifiDenied:
print("ReachabilityService: unsatisfiedReason: wifiDenied")
break
case .localNetworkDenied:
print("ReachabilityService: unsatisfiedReason: localNetworkDenied")
break
@unknown default:
print("ReachabilityService: unsatisfiedReason: default")
}
} else {
// Fallback on earlier versions
}
self?.isNetworkAvailable = false
break
case .requiresConnection:
print("ReachabilityService: requiresConnection")
self?.isNetworkAvailable = false
break
@unknown default:
print("ReachabilityService: default")
self?.isNetworkAvailable = false
}
if path.usesInterfaceType(.wifi) {
self?.typeOfCurrentConnection = .wifi
} else if path.usesInterfaceType(.cellular) {
self?.typeOfCurrentConnection = .cellular
} else if path.usesInterfaceType(.loopback) {
self?.typeOfCurrentConnection = .loopBack
} else if path.usesInterfaceType(.wiredEthernet) {
self?.typeOfCurrentConnection = .wired
} else if path.usesInterfaceType(.other) {
self?.typeOfCurrentConnection = .other
}
}
monitor.start(queue: backgroundQueue)
}
}
Usage:
In your view model:
private let reachability = ReachabilityService()
init() {
reachability.$isNetworkAvailable.sink { [weak self] isConnected in
self?.isConnected = isConnected ?? false
}.store(in: &cancelBag)
}
In your controller:
viewModel.$isConnected.sink { [weak self] isConnected in
print("isConnected: \(isConnected)")
DispatchQueue.main.async {
//Update your UI in here
}
}.store(in: &bindings)
@Inherently Curious - thanks for posting this. You are almost there - you have to add two more params to SSLContext.init() method.
TrustManager[] trustManagers = new TrustManager[] { new TrustManagerManipulator() };
sc.init(null, trustManagers, new SecureRandom());
it will start working. Again thank you very much for posting this. I solved this/my issue with your code.
Just from reading what you have written, you will need to add the file class.phpmailer.php to your directory as well.
+ theme(plot.title = element_text(size=22))
Here is the full set of things you can change in element_text
:
element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
color = NULL)
Something like this - a riff on @maarten-vanlinthout's answer
ip -f inet a show eth0| grep inet| awk '{ print $2}' | cut -d/ -f1
If you need this for CocoaPods targets add this lines in Podfile
:
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
target.build_settings(config.name)['CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES'] = 'YES'
end
end
end
This one did work for me in ES 1.7.5:
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
public static void main(String[] args) throws IOException {
Settings settings = ImmutableSettings.settingsBuilder()
.put("client.transport.sniff",true)
.put("cluster.name","elasticcluster").build();
Client client = new TransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress("[ipaddress]",9300));
XContentBuilder builder = null;
try {
builder = jsonBuilder().startObject().field("user", "testdata").field("postdata",new Date()).field("message","testmessage")
.endObject();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(builder.string());
IndexResponse response = client.prepareIndex("twitter","tweet","1").setSource(builder).execute().actionGet();
client.close();
}
This is the Scala solution if anyone needs it
def anUnsafeOkHttpClient(): OkHttpClient = {
val manager: TrustManager =
new X509TrustManager() {
override def checkClientTrusted(x509Certificates: Array[X509Certificate], s: String) = {}
override def checkServerTrusted(x509Certificates: Array[X509Certificate], s: String) = {}
override def getAcceptedIssuers = Seq.empty[X509Certificate].toArray
}
val trustAllCertificates = Seq(manager).toArray
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCertificates, new java.security.SecureRandom())
val sslSocketFactory = sslContext.getSocketFactory()
val okBuilder = new OkHttpClient.Builder()
okBuilder.sslSocketFactory(sslSocketFactory, trustAllCertificates(0).asInstanceOf[X509TrustManager])
okBuilder.hostnameVerifier(new NoopHostnameVerifier)
okBuilder.build()
}
Your function has a couple of smallint
parameters.
But in the call, you are using numeric literals that are presumed to be type integer
.
A string literal or string constant ('123'
) is not typed immediately. It remains type "unknown" until assigned or cast explicitly.
However, a numeric literal or numeric constant is typed immediately. Per documentation:
A numeric constant that contains neither a decimal point nor an exponent is initially presumed to be type
integer
if its value fits in typeinteger
(32 bits); otherwise it is presumed to be typebigint
if its value fits in typebigint
(64 bits); otherwise it is taken to be typenumeric
. Constants that contain decimal points and/or exponents are always initially presumed to be typenumeric
.
More explanation and links in this related answer:
Add explicit casts for the smallint
parameters or quote them.
CREATE OR REPLACE FUNCTION f_typetest(smallint)
RETURNS bool AS 'SELECT TRUE' LANGUAGE sql;
Incorrect call:
SELECT * FROM f_typetest(1);
Correct calls:
SELECT * FROM f_typetest('1');
SELECT * FROM f_typetest(smallint '1');
SELECT * FROM f_typetest(1::int2);
SELECT * FROM f_typetest('1'::int2);
db<>fiddle here
Old sqlfiddle.
Two methods:
You need to ask for the IP address that is bound to your eth0
interface. This is available from the netifaces package
import netifaces as ni
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
print ip # should print "192.168.100.37"
You can also get a list of all available interfaces via
ni.interfaces()
Here's a way to get the IP address without using a python package:
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
get_ip_address('eth0') # '192.168.0.110'
Note: detecting the IP address to determine what environment you are using is quite a hack. Almost all frameworks provide a very simple way to set/modify an environment variable to indicate the current environment. Try and take a look at your documentation for this. It should be as simple as doing
if app.config['ENV'] == 'production':
#send production email
else:
#send development email
I think you should use SO_LINGER options (with timeout 0). In this case, you connection will close immediately after closing your program; and next restart will be able to bind again.
example:
linger lin;
lin.l_onoff = 0;
lin.l_linger = 0;
setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char *)&lin, sizeof(int));
see definition: http://man7.org/linux/man-pages/man7/socket.7.html
SO_LINGER
Sets or gets the SO_LINGER option. The argument is a linger
structure.
struct linger {
int l_onoff; /* linger active */
int l_linger; /* how many seconds to linger for */
};
When enabled, a close(2) or shutdown(2) will not return until
all queued messages for the socket have been successfully sent
or the linger timeout has been reached. Otherwise, the call
returns immediately and the closing is done in the background.
When the socket is closed as part of exit(2), it always
lingers in the background.
More about SO_LINGER: TCP option SO_LINGER (zero) - when it's required
To add an exclusion for logback from Netbeans IDE
Right click on the jar and select Exclude Dependency as shown below. This excludes the logback jar on the pom.xml like this;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
You can do as follows
ifconfig <Interface ex:eth0,eth1> | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'
Also you can get MAC for all interface as follows
cat /sys/class/net/*/address
For particular interface like for eth0
cat /sys/class/net/eth0/address
Control Panel >> Windows Firewall
Advanced settings >> Inbound Rules >> World Wide Web Services - Enable it All or (Domain, Private, Public) as needed.
you need /q at the end
MsiExec.exe /x {2F808931-D235-4FC7-90CD-F8A890C97B2F} /q
If the goal is to find the IP address connected in direction of internet, then this should be a good solution.
UPDATE!!! With new version of linux you get more information on the line:
ip route get 8.8.8.8
8.8.8.8 via 10.36.15.1 dev ens160 src 10.36.15.150 uid 1002
cache
so to get IP you need to find the IP after src
ip route get 8.8.8.8 | awk -F"src " 'NR==1{split($2,a," ");print a[1]}'
10.36.15.150
and if you like the interface name
ip route get 8.8.8.8 | awk -F"dev " 'NR==1{split($2,a," ");print a[1]}'
ens192
ip route
does not open any connection out, it just shows the route needed to get to 8.8.8.8
. 8.8.8.8
is Google's DNS.
If you like to store this into a variable, do:
my_ip=$(ip route get 8.8.8.8 | awk -F"src " 'NR==1{split($2,a," ");print a[1]}')
my_interface=$(ip route get 8.8.8.8 | awk -F"dev " 'NR==1{split($2,a," ");print a[1]}')
Why other solution may fail:
ifconfig eth0
Hostname -I
I think you are missing your certificates.
You can try generating them by using InstallCerts app. Here you can see how to use it: https://github.com/escline/InstallCert
Once you get your certificate, you need to put it under your security directory within your jdk home, for example:
C:\Program Files\Java\jdk1.6.0_45\jre\lib\security
Let me know if it works.
import socket
from threading import *
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))
class client(Thread):
def __init__(self, socket, address):
Thread.__init__(self)
self.sock = socket
self.addr = address
self.start()
def run(self):
while 1:
print('Client sent:', self.sock.recv(1024).decode())
self.sock.send(b'Oi you sent something to me')
serversocket.listen(5)
print ('server started and listening')
while 1:
clientsocket, address = serversocket.accept()
client(clientsocket, address)
This is a very VERY simple design for how you could solve it.
First of all, you need to either accept the client (server side) before going into your while 1
loop because in every loop you accept a new client, or you do as i describe, you toss the client into a separate thread which you handle on his own from now on.
The type 'Domain.tblUser' is defined in an assembly that is not referenced. You must add a reference to assembly 'Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
**Solved:**
Add reference of my domain library layer to my web app libary layer
Note: Make sure your references are correct according to you DI container
The code works for me. (after adding missing except
clause / import
statements)
Did you put \
in the original code?
urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
+ stock + '/chartdata;type=quote;range=5d/csv'
If you omit it, it could be a cause of the exception:
>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
BTW, string(e)
should be str(e)
.
If you are on mac try this :
cd Users/<Your name>
Make sure that you are on the right path by looking for .gradle with
ls -la
then run that to delete .gradle
rm -rf .gradle
This will remove everything. Then launch your commande again and it will work !
It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.
Well, we're using Amazon Web Services and so we are looking to use scripts and programs to get through this problem. So I have been on the hunt for a command line tool. So first I tried the trick of running
c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
but because I'm running a cloud based Windows Server 2012 it complained
This option is not supported on this version of the operating system. Administrators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Windows Features On/Off" dialog, the Server Manager management tool, or the dism.exe command line tool. For more details please see http://go.microsoft.com/fwlink/?LinkID=216771.
and I Googled and found the official Microsoft Support Page KB2736284. So there is a command line tool dism.exe
. So I tried the following
dism /online /enable-feature /featurename:IIS-ASPNET45
but it complained and gave a list of featurenames to try, so I tried them one by one and I tested my WebAPI webpage after each and it worked after the bottom one in the list.
dism /online /enable-feature /featurename:IIS-ApplicationDevelopment
dism /online /enable-feature /featurename:IIS-ISAPIFilter
dism /online /enable-feature /featurename:IIS-ISAPIExtensions
dism /online /enable-feature /featurename:IIS-NetFxExtensibility45
And so now I can browse to my WebAPI site and see the API information. That should help a few people. [However, I am not out of the woods totally myself yet and I cannot reach the website from outside the box. Still working on it.]
Also, I did some earlier steps following other people responses. I can confirm that the following Feature Delegation needs to be change (though I'd like to find a command line tool for these).
In Feature delegation
Change
'Handler Mappings' from Read Only to Read/Write
Change
'Modules' from Read Only to Read/Write
Change
'SSL Settings' from Read Only to Read/Write
I had the same problem. java.net.UnknownHostException: Unable to resolve host “”...
I'm running Visual Studio 2019 and Xamarin.
I also switched back to my WiFi but was on a hot spot.
I solved this by clean swiping the emulator. Restore to factory settings. Then re-running visual studio xamarin app which wil redeploy your app again to the fresh emulator.
It worked. I thought I was going to battle for days to solve this. Luckily this post pointed me in the right direction.
I could not understand how it worked perfectly before and then stopped with no code change.
This is my code for reference:
using var response = await httpClient.GetAsync(sb.ToString());
string apiResponse = await response.Content.ReadAsStringAsync();
Another cause for this is if you have the same database restored under a different name. Delete the existing one and then restoring solved it for me.
Use python library called num2words
Link -> HERE
when you bind localhost
or 127.0.0.1
, it means you can only connect to your service from local.
you cannot bind 10.0.0.1
because it not belong to you, you can only bind ip owned by your computer
you can bind 0.0.0.0
because it means all ip on your computer, so any ip can connect to your service if they can connect to any of your ip
It is done to maintain the arrangement of bytes which is sent in the network(Endianness). Depending upon architecture of your device,data can be arranged in the memory either in the big endian format or little endian format. In networking, we call the representation of byte order as network byte order and in our host, it is called host byte order. All network byte order is in big endian format.If your host's memory computer architecture is in little endian format,htons() function become necessity but in case of big endian format memory architecture,it is not necessary.You can find endianness of your computer programmatically too in the following way:->
int x = 1;
if (*(char *)&x){
cout<<"Little Endian"<<endl;
}else{
cout<<"Big Endian"<<endl;
}
and then decide whether to use htons() or not.But in order to avoid the above line,we always write htons() although it does no changes for Big Endian based memory architecture.
There is no bound checking in array in C programming. If you declare array as
int arr[50];
Then you can even write as
arr[51] = 10;
The compiler would not throw an error. Hope this answers your question.
In my case on macOS I solved it with:
brew link libtool
Did you consider using nginx (or other event based web server) instead of apache?
nginx shall allow higher number of connections and consume much less resources (as it is event based and does not create separate process per connection). Anyway, you will need some processes, doing real work (like WSGI servers or so) and if they stay on the same server as the front end web server, you only shift the performance problem to a bit different place.
Latest apache version shall allow similar solution (configure it in event based manner), but this is not my area of expertise.
With Python3x, you need to convert your string to raw bytes. You would have to encode the string as bytes. Over the network you need to send bytes and not characters. You are right that this would work for Python 2x since in Python 2x, socket.sendto on a socket takes a "plain" string and not bytes. Try this:
print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))
Using name on a select option is not valid.
Other have suggested the data- attribute, an alternative is a lookup table
Here the "this" refers to the select so no need to "find" the option
var names = ["", "acoustic", "jazz", "acoustic_jazz", "party", "acoustic_party", "jazz_party", "acoustic_jazz_party"];_x000D_
_x000D_
$(function() {_x000D_
$('#band_type_choices').on('change', function() {_x000D_
$('.checkboxlist').hide();_x000D_
var idx = this.selectedIndex;_x000D_
if (idx > 0) $('#checkboxlist_' + names[idx]).show();_x000D_
});_x000D_
});
_x000D_
.checkboxlist { display:none }
_x000D_
Choose acoustic to see the corresponding div_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id="band_type_choices">_x000D_
<option vlaue="0"></option>_x000D_
<option value="100" name="acoustic">Acoustic</option>_x000D_
<option value="0" name="jazz">Jazz/Easy Listening</option>_x000D_
<option value="0" name="acoustic_jazz">Acoustic + Jazz/Easy Listening</option>_x000D_
<option value="0" name="party">Party</option>_x000D_
<option value="0" name="acoustic_party">Acoustic + Party</option>_x000D_
<option value="0" name="jazz_party">Jazz/Easy Listening + Party</option>_x000D_
<option value="0" name="acoustic_jazz_party">Acoustic + Jazz/Easy Listening + Party</option>_x000D_
</select>_x000D_
<div class="checkboxlist" id="checkboxlist_acoustic">_x000D_
<input type="checkbox" class="checkbox keys" name="keys" value="100" />Keys<br>_x000D_
<input type="checkbox" class="checkbox acou_guit" name="acou_guit" value="100" />Acoustic Guitar<br>_x000D_
<input type="checkbox" class="checkbox drums" name="drums" value="100" />Drums<br>_x000D_
<input type="checkbox" class="checkbox alt_sax" name="alt_sax" value="100" />Alto Sax<br>_x000D_
<input type="checkbox" class="checkbox ten_sax" name="ten_sax" value="100" />Tenor Sax<br>_x000D_
<input type="checkbox" class="checkbox clarinet" name="clarinet" value="100" />Clarinet<br>_x000D_
<input type="checkbox" class="checkbox trombone" name="trombone" value="100" />Trombone<br>_x000D_
<input type="checkbox" class="checkbox trumpet" name="trumpet" value="100" />Trumpet<br>_x000D_
<input type="checkbox" class="checkbox flute" name="flute" value="100" />Flute<br>_x000D_
<input type="checkbox" class="checkbox cello" name="cello" value="100" />Cello<br>_x000D_
<input type="checkbox" class="checkbox violin" name="violin" value="100" />Violin<br>_x000D_
</div>
_x000D_
XCode2: sudo xcode-select -s /Applications/Xcode\ 2.app/Contents/Developer
Pay attention to the "\" to escape the space
Disclaimer: There are very rare cases in which you really need to do this. If possible use an existing application layer protocol or define your own eg. precede each message with a fixed length integer indicating the length of data that follows or terminate each message with a '\n' character. (Adam Rosenfield's answer does a really good job at explaining that)
With that said, there is a way to read all of the data available on a socket. However, it is a bad idea to rely on this kind of communication as it introduces the risk of loosing data. Use this solution with extreme caution and only after reading the explanation below.
def recvall(sock):
BUFF_SIZE = 4096
data = bytearray()
while True:
packet = sock.recv(BUFF_SIZE)
if not packet: # Important!!
break
data.extend(packet)
return data
Now the if not packet:
line is absolutely critical!
Many answers here suggested using a condition like which is broken and will most likely cause you to close your connection prematurely and loose data. It wrongly assumes that one send on one end of a TCP socket corresponds to one receive of sent number of bytes on the other end. It does not. There is a very good chance that if len(packet) < BUFF_SIZE:
sock.recv(BUFF_SIZE)
will return a chunk smaller than BUFF_SIZE
even if there's still data waiting to be received. There is a good explanation of the issue here and here.
By using the above solution you are still risking data loss if the other end of the connection is writing data slower than you are reading. You may just simply consume all data on your end and exit when more is on the way. There are ways around it that require the use of concurrent programming, but that's another topic of its own.
You can use netstat command
netstat --listen
To display open ports and established TCP connections,
netstat -vatn
To display only open UDP ports try the following command:
netstat -vaun
You need to make sure the IIS Management Console is installed.
Just like Tom mentioned. When you start with capital A
then autocomplete will complete it as.
ANDROID.PERMISSION.INTERNET
When you start typing with a
then autocomplete will complete it as
android.permission.INTERNET
The second one is the correct one.
Make sure the scp command is available on both sides - both on the client and on the server.
If this is Fedora or Red Hat Enterprise Linux and clones (CentOS), make sure this package is installed:
yum -y install openssh-clients
If you work with Debian or Ubuntu and clones, install this package:
apt-get install openssh-client
Again, you need to do this both on the server and the client, otherwise you can encounter "weird" error messages on your client: scp: command not found
or similar although you have it locally. This already confused thousands of people, I guess :)
I solved it by doing the following:
In Visual studio I went in Project -> Project Dependencies
I selected the XXX.Test
solution and told it that it also depends on the XXX
solution to make the post-build
events in the XXX.Test
solution not generate this error (exit with code 4
).
Installing ASP.NET Core Runtime Hosting Bundle solved the issue for me. Source: 500.19 Internal Server Error (0x8007000d)
You can try like:
var path="~/Image/test.png"; System.Web.Hosting.HostingEnvironment.MapPath( @ + path)
first import os module in your app than with use from getpid function get pid's app and save in a file.for example :
import os
pid = os.getpid()
op = open("/var/us.pid","w")
op.write("%s" % pid)
op.close()
and create a bash file in /etc/init.d path: /etc/init.d/servername
PATHAPP="/etc/bin/userscript.py &"
PIDAPP="/var/us.pid"
case $1 in
start)
echo "starting"
$(python $PATHAPP)
;;
stop)
echo "stoping"
PID=$(cat $PIDAPP)
kill $PID
;;
esac
now , u can start and stop ur app with down command:
service servername stop service servername start
or
/etc/init.d/servername stop /etc/init.d/servername start
Run these codes in thread or AsyncTask. In order to avoid duplicated callings of same _url(one time for getContentLength(), one time of openStream()), use IOUtils.toByteArray of Apache.
void downloadFile(String _url, String _name) {
try {
URL u = new URL(_url);
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = IOUtils.toByteArray(stream);
FileOutputStream fos = mContext.openFileOutput(_name, Context.MODE_PRIVATE);
fos.write(buffer);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
}
this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.
to check either a pointer is initialized or not you can try something like
Class *pointer = new Class();
if(pointer!=nullptr){
pointer->myFunction();
}
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
We use the Url Rewrite extension for IIS for redirecting all HTTP requests to HTTPS. When trying to call a service not using transport security on an http://... address, this is the error that appeared.
So it might be worth checking if you can hit both the http and https addresses of the service via a browser and that it doesn't auto forward you with a 303 status code.
My problem was solved that way:
Your username is probably restricted, You must grant full access to the user.
May be helpful for somebody. Mocked method must be of mocked class, created with mock(MyService.class)
Update: Looks like this is more useful than I thought. I've just published this on npm. https://www.npmjs.com/package/num-words
Here's a shorter code. with one RegEx and no loops. converts as you wanted, in south asian numbering system
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];_x000D_
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];_x000D_
_x000D_
function inWords (num) {_x000D_
if ((num = num.toString()).length > 9) return 'overflow';_x000D_
n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);_x000D_
if (!n) return; var str = '';_x000D_
str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';_x000D_
str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';_x000D_
str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';_x000D_
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';_x000D_
str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'only ' : '';_x000D_
return str;_x000D_
}_x000D_
_x000D_
document.getElementById('number').onkeyup = function () {_x000D_
document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);_x000D_
};
_x000D_
<span id="words"></span>_x000D_
<input id="number" type="text" />
_x000D_
The only limitation is, you can convert maximum of 9 digits, which I think is more than sufficient in most cases..
As far as I'm aware Ratchet is the best PHP WebSocket solution available at the moment. And since it's open source you can see how the author has built this WebSocket solution using PHP.
Canvas does not using .png file as background image. changing to other file extensions like gif or jpg works fine.
Try:
Qty1 : <input onblur="findTotal()" type="text" name="qty" id="qty1"/><br>
Qty2 : <input onblur="findTotal()" type="text" name="qty" id="qty2"/><br>
Qty3 : <input onblur="findTotal()" type="text" name="qty" id="qty3"/><br>
Qty4 : <input onblur="findTotal()" type="text" name="qty" id="qty4"/><br>
Qty5 : <input onblur="findTotal()" type="text" name="qty" id="qty5"/><br>
Qty6 : <input onblur="findTotal()" type="text" name="qty" id="qty6"/><br>
Qty7 : <input onblur="findTotal()" type="text" name="qty" id="qty7"/><br>
Qty8 : <input onblur="findTotal()" type="text" name="qty" id="qty8"/><br>
<br><br>
Total : <input type="text" name="total" id="total"/>
<script type="text/javascript">
function findTotal(){
var arr = document.getElementsByName('qty');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('total').value = tot;
}
</script>
You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function
I changed the port from 80 to 8080, that's why this error occur. I write localhost/ in search bar then this error occur. My problem is resolved by writing localhost:8080/ in the search then local host open.
Default: 5672, the manual has the answer. It's defined in the RABBITMQ_NODE_PORT
variable.
https://www.rabbitmq.com/configure.html#define-environment-variables
The number might be differently if changed by someone in the rabbitmq configuration file:
vi /etc/rabbitmq/rabbitmq-env.conf
Ask the computer to tell you:
sudo nmap -p 1-65535 localhost
Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:50 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00041s latency).
PORT STATE SERVICE
443/tcp open https
5672/tcp open amqp
15672/tcp open unknown
35102/tcp open unknown
59440/tcp open unknown
Oh look, 5672, and 15672
Use netstat:
netstat -lntu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:15672 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:55672 0.0.0.0:* LISTEN
tcp 0 0 :::5672 :::* LISTEN
Oh look 5672.
use lsof:
eric@dev ~$ sudo lsof -i | grep beam
beam.smp 21216 rabbitmq 17u IPv4 33148214 0t0 TCP *:55672 (LISTEN)
beam.smp 21216 rabbitmq 18u IPv4 33148219 0t0 TCP *:15672 (LISTEN)
use nmap from a different machine, find out if 5672 is open:
sudo nmap -p 5672 10.0.1.71
Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:19 EDT
Nmap scan report for 10.0.1.71
Host is up (0.00011s latency).
PORT STATE SERVICE
5672/tcp open amqp
MAC Address: 0A:40:0E:8C:75:6C (Unknown)
Nmap done: 1 IP address (1 host up) scanned in 0.13 seconds
Try to connect to a port manually with telnet, 5671 is CLOSED:
telnet localhost 5671
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
Try to connect to a port manually with telnet, 5672 is OPEN:
telnet localhost 5672
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Check your firewall:
sudo cat /etc/sysconfig/iptables
It should tell you what ports are made open:
-A INPUT -p tcp -m tcp --dport 5672 -j ACCEPT
Reapply your firewall:
sudo service iptables restart
iptables: Setting chains to policy ACCEPT: filter [ OK ]
iptables: Flushing firewall rules: [ OK ]
iptables: Unloading modules: [ OK ]
iptables: Applying firewall rules: [ OK ]
You need to include inttypes.h
if you want all those nifty new format specifiers for the intN_t
types and their brethren, and that is the correct (ie, portable) way to do it, provided your compiler complies with C99. You shouldn't use the standard ones like %d
or %u
in case the sizes are different to what you think.
It includes stdint.h
and extends it with quite a few other things, such as the macros that can be used for the printf/scanf
family of calls. This is covered in section 7.8 of the ISO C99 standard.
For example, the following program:
#include <stdio.h>
#include <inttypes.h>
int main (void) {
uint32_t a=1234;
uint16_t b=5678;
printf("%" PRIu32 "\n",a);
printf("%" PRIu16 "\n",b);
return 0;
}
outputs:
1234
5678
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
I had enough success just catchig socket.timeout
and socket.error
; although socket.error can be raised for lots of reasons. Be careful.
import socket
import logging
hostname='google.com'
port=443
try:
sock = socket.create_connection((hostname, port), timeout=3)
except socket.timeout as err:
logging.error(err)
except socket.error as err:
logging.error(err)
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
I prefer to this way:
/**
*
* @param host
* @return true means ping success,false means ping fail.
* @throws IOException
* @throws InterruptedException
*/
private static boolean ping(String host) throws IOException, InterruptedException {
boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");
ProcessBuilder processBuilder = new ProcessBuilder("ping", isWindows? "-n" : "-c", "1", host);
Process proc = processBuilder.start();
return proc.waitFor(200, TimeUnit.MILLISECONDS);
}
This way can limit the blocking time to the specific time,such as 200 ms.
It works well in MacOS?Android and Windows, but should used in JDK 1.8.
This idea comes from Mohammad Banisaeid,but I can't comment. (You must have 50 reputation to comment)
Instead of using this
as the accepted answer suggests, use $parent
instead. So in your partial1.html
you'll have:
<form ng-submit="$parent.addLine()">
<input type="text" ng-model="$parent.lineText" size="30" placeholder="Type your message here">
</form>
If you want to learn more about the scope in ng-include
or other directives, check this out: https://github.com/angular/angular.js/wiki/Understanding-Scopes#ng-include
I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!!
use close(fd)
system call after you finished working on a file.
This should work for you
public class MyActivity extends Activity {
protected ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populateTable();
}
private void populateTable() {
mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
new Thread() {
@Override
public void run() {
doLongOperation();
try {
// code runs in a thread
runOnUiThread(new Runnable() {
@Override
public void run() {
mProgressDialog.dismiss();
}
});
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
}.start();
}
/** fake operation for testing purpose */
protected void doLongOperation() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
}
}
An alternative to theme_classic()
is the theme that comes with the cowplot package, theme_cowplot()
(loaded automatically with the package). It looks similar to theme_classic()
, with a few subtle differences. Most importantly, the default label sizes are larger, so the resulting figures can be used in publications without further modifications needed (in particular if you save them with save_plot()
instead of ggsave()
). Also, the background is transparent, not white, which may be useful if you want to edit the figure in illustrator. Finally, faceted plots look better, in my opinion.
Example:
library(cowplot)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
p <- ggplot(df, aes(x = a, y = b)) + geom_point()
save_plot('plot.png', p) # alternative to ggsave, with default settings that work well with the theme
This is what the file plot.png
produced by this code looks like:
Disclaimer: I'm the package author.
ACCESSING LOCAL WEBSITE WITH IIS without Physical Path Authentication
I hope it helps. That's what I did.
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
Based off of @Mike Sherrill Cat Recall's answer, this is what worked for me:
ALTER TABLE "Children"
DROP CONSTRAINT "Children_parentId_fkey",
ADD CONSTRAINT "Children_parentId_fkey"
FOREIGN KEY ("parentId")
REFERENCES "Parent"(id)
ON DELETE CASCADE;
To make it work I build my directory like this:
Project Public Restrict
So I edited my webconfig for my public folder:
<location path="Project/Public">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
And for my Restricted folder:
<location path="Project/Restricted">
<system.web>
<authorization>
<allow users="*"/>
</authorizatio>
</system.web>
</location>
See here for the spec of * and ?:
https://docs.microsoft.com/en-us/iis/configuration/system.webserver/security/authorization/add
I hope I have helped.
Try to go to App_Data folder property and add ASPNET user with read and write privileges
Ref:
How to assign correct permissions to App_Data folder of WebMail Pro ASP.NET
Permissions on APP_DATA Folder
ASP/ASP.NET Best way to handle write permissions?
If it does not solve your problem then check whether your XML files are not open by another thread using these configuration files.. and provide some more details if still persists.
A Swift3 version:
extension UIView {
func startRotate() {
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = NSNumber(value: M_PI * 2)
rotation.duration = 2
rotation.isCumulative = true
rotation.repeatCount = FLT_MAX
self.layer.add(rotation, forKey: "rotationAnimation")
}
func stopRotate() {
self.layer.removeAnimation(forKey: "rotationAnimation")
}
}
And remember to call startRotate
in viewWillAppear
not in viewDidLoad
.
You can use java's InetAddress class for this purpose.
InetAddress IP=InetAddress.getLocalHost();
System.out.println("IP of my system is := "+IP.getHostAddress());
Output for my system = IP of my system is := 10.100.98.228
getHostAddress() returns
Returns the IP address string in textual presentation.
OR you can also do
InetAddress IP=InetAddress.getLocalHost();
System.out.println(IP.toString());
Output = IP of my system is := RanRag-PC/10.100.98.228
If you are running IIS 8 with windows server 2012 you need to do the following:
from then on your application should start running
This does the job without any library. Used recursion and it is Indian style. -- Ravi.
def spellNumber(no):
# str(no) will result in 56.9 for 56.90 so we used the method which is given below.
strNo = "%.2f" %no
n = strNo.split(".")
rs = numberToText(int(n[0])).strip()
ps =""
if(len(n)>=2):
ps = numberToText(int(n[1])).strip()
rs = "" + ps+ " paise" if(rs.strip()=="") else (rs + " and " + ps+ " paise").strip()
return rs
print(spellNumber(0.67))
print(spellNumber(5858.099))
print(spellNumber(5083754857380.50))
def numberToText(no):
ones = " ,one,two,three,four,five,six,seven,eight,nine,ten,eleven,tweleve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen,twenty".split(',')
tens = "ten,twenty,thirty,fourty,fifty,sixty,seventy,eighty,ninety".split(',')
text = ""
if len(str(no))<=2:
if(no<20):
text = ones[no]
else:
text = tens[no//10-1] +" " + ones[(no %10)]
elif len(str(no))==3:
text = ones[no//100] +" hundred " + numberToText(no- ((no//100)* 100))
elif len(str(no))<=5:
text = numberToText(no//1000) +" thousand " + numberToText(no- ((no//1000)* 1000))
elif len(str(no))<=7:
text = numberToText(no//100000) +" lakh " + numberToText(no- ((no//100000)* 100000))
else:
text = numberToText(no//10000000) +" crores " + numberToText(no- ((no//10000000)* 10000000))
return text
In any case, your code will generate invalid markup: You shouldn't wrap block contents in a link. tags don't work like this. If you want this effect you should use js or create an absolutely positioned link above the content (z-index). More on this here: Make a div into a link.
You should make sure to validate your code when it renders: http://validator.w3.org
Sorry, but all the answers are difficult to understand for me as a beginner in graphics...
After some fiddling, this is working for me and it is easy to reason about.
@Override
public void draw(Graphics2D g) {
AffineTransform tr = new AffineTransform();
// X and Y are the coordinates of the image
tr.translate((int)getX(), (int)getY());
tr.rotate(
Math.toRadians(this.rotationAngle),
img.getWidth() / 2,
img.getHeight() / 2
);
// img is a BufferedImage instance
g.drawImage(img, tr, null);
}
I suppose that if you want to rotate a rectangular image this method wont work and will cut the image, but I thing you should create square png images and rotate that.
You can also use the following command:
ip route | grep src
NOTE: This will only work if you have connectivity to the internet.
This is actually not an error... What happens here is that Mongo relies on a daemon in order to run the local database server, so in order to "fire up" the mongo server in your shell, you have to start the mongo service first.
For Fedora Linux (wich is the Distro I use) You have to run these commands:
1 sudo service mongod start
2 mongo
And there you have it! the server is going to run. Now, If you want Mongo service to Start when the system boots then you have to run:
sudo chkconfig --levels 235 mongod on
And that's all! If you do that, now in the shell you just have to type mongo in order to start the server but that's pretty much it, the problem is you have to start the SERVICE first and then the SERVER :)
P.S. The commands I posted might work on other linux distros as well, not just in fedora... In case not maybe you have to tweak some words depending on the distro you're using ;)
The computer "name" is resolved from the IP address by the underlying DNS (Domain Name System) library of the OS. There's no universal concept of a computer name across OSes, but DNS is generally available. If the computer name hasn't been configured so DNS can resolve it, it isn't available.
import java.net.InetAddress;
import java.net.UnknownHostException;
String hostname = "Unknown";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
An Internet Information Services (IIS) worker process is a windows process (w3wp.exe) which runs Web applications, and is responsible for handling requests sent to a Web Server for a specific application pool.
It is the worker process for IIS. Each application pool creates at least one instance of w3wp.exe
and that is what actually processes requests in your application. It is not dangerous to attach to this, that is just a standard windows message.
This should do the job
//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");
//draw a dot
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
It looks like your client is trying to connect to a non-existent server. In a shell window, run:
$ nc -l 5000
before running your Python code. It will act as a server listening on port 5000 for you to connect to. Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa.
OpenSSL is quite difficult. It's easy to accidentally throw away all your security by not doing negotiation exactly right. (Heck, I've been personally bitten by a bug where curl wasn't reading the OpenSSL alerts exactly right, and couldn't talk to some sites.)
If you really want quick and simple, put stud in front of your program an call it a day. Having SSL in a different process won't slow you down: http://vincent.bernat.im/en/blog/2011-ssl-benchmark.html
Okay, my problem wasn't the port, but the binding address. My server has an internal address (10.0.0.4) and an external address (52.175.223.XX). When I tried connecting with:
$sock = @stream_socket_server('tcp://52.175.223.XX:123', $errNo, $errStr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN);
It failed because the local socket was 10.0.0.4 and not the external 52.175.223.XX. You can checkout the local available interfaces with sudo ifconfig
.
All you need is a <clear />
tag. Here's an example:
<configuration>
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="default.aspx" />
</files>
</defaultDocument>
</system.webServer>
</configuration>
As others have noted, getting the hostname based on DNS resolution is unreliable.
Since this question is unfortunately still relevant in 2018, I'd like to share with you my network-independent solution, with some test runs on different systems.
The following code tries to do the following:
On Windows
Read the COMPUTERNAME
environment variable through System.getenv()
.
Execute hostname.exe
and read the response
On Linux
Read the HOSTNAME
environment variable through System.getenv()
Execute hostname
and read the response
Read /etc/hostname
(to do this I'm executing cat
since the snippet already contains code to execute and read. Simply reading the file would be better, though).
The code:
public static void main(String[] args) throws IOException {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
System.out.println("Windows computer name through env:\"" + System.getenv("COMPUTERNAME") + "\"");
System.out.println("Windows computer name through exec:\"" + execReadToString("hostname") + "\"");
} else if (os.contains("nix") || os.contains("nux") || os.contains("mac os x")) {
System.out.println("Unix-like computer name through env:\"" + System.getenv("HOSTNAME") + "\"");
System.out.println("Unix-like computer name through exec:\"" + execReadToString("hostname") + "\"");
System.out.println("Unix-like computer name through /etc/hostname:\"" + execReadToString("cat /etc/hostname") + "\"");
}
}
public static String execReadToString(String execCommand) throws IOException {
try (Scanner s = new Scanner(Runtime.getRuntime().exec(execCommand).getInputStream()).useDelimiter("\\A")) {
return s.hasNext() ? s.next() : "";
}
}
Results for different operating systems:
macOS 10.13.2
Unix-like computer name through env:"null"
Unix-like computer name through exec:"machinename
"
Unix-like computer name through /etc/hostname:""
OpenSuse 13.1
Unix-like computer name through env:"machinename"
Unix-like computer name through exec:"machinename
"
Unix-like computer name through /etc/hostname:""
Ubuntu 14.04 LTS
This one is kinda strange since echo $HOSTNAME
returns the correct hostname, but System.getenv("HOSTNAME")
does not:
Unix-like computer name through env:"null"
Unix-like computer name through exec:"machinename
"
Unix-like computer name through /etc/hostname:"machinename
"
EDIT: According to legolas108, System.getenv("HOSTNAME")
works on Ubuntu 14.04 if you run export HOSTNAME
before executing the Java code.
Windows 7
Windows computer name through env:"MACHINENAME"
Windows computer name through exec:"machinename
"
Windows 10
Windows computer name through env:"MACHINENAME"
Windows computer name through exec:"machinename
"
The machine names have been replaced but I kept the capitalization and structure. Note the extra newline when executing hostname
, you might have to take it into account in some cases.
If you want to determine the equation of the curve through n points then the following code will give you the coefficients of the polynomial of degree n-1 and save these coefficients to the coefficients[]
array (starting from the constant term). The x coordinates do not have to be in order. This is an example of a Lagrange polynomial.
var xPoints=[2,4,3,6,7,10]; //example coordinates
var yPoints=[2,5,-2,0,2,8];
var coefficients=[];
for (var m=0; m<xPoints.length; m++) coefficients[m]=0;
for (var m=0; m<xPoints.length; m++) {
var newCoefficients=[];
for (var nc=0; nc<xPoints.length; nc++) newCoefficients[nc]=0;
if (m>0) {
newCoefficients[0]=-xPoints[0]/(xPoints[m]-xPoints[0]);
newCoefficients[1]=1/(xPoints[m]-xPoints[0]);
} else {
newCoefficients[0]=-xPoints[1]/(xPoints[m]-xPoints[1]);
newCoefficients[1]=1/(xPoints[m]-xPoints[1]);
}
var startIndex=1;
if (m==0) startIndex=2;
for (var n=startIndex; n<xPoints.length; n++) {
if (m==n) continue;
for (var nc=xPoints.length-1; nc>=1; nc--) {
newCoefficients[nc]=newCoefficients[nc]*(-xPoints[n]/(xPoints[m]-xPoints[n]))+newCoefficients[nc-1]/(xPoints[m]-xPoints[n]);
}
newCoefficients[0]=newCoefficients[0]*(-xPoints[n]/(xPoints[m]-xPoints[n]));
}
for (var nc=0; nc<xPoints.length; nc++) coefficients[nc]+=yPoints[m]*newCoefficients[nc];
}
i got this error because I closed ServerSocket
inside a for loop that try to accept number of clients inside it (I did not finished accepting all clints)
so be careful where to close your Socket
I have the same problem with Yandex Maps server, JDK 1.6 and Apache HttpClient 4.2.1. The error was
javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
with enabled debug by -Djavax.net.debug=all
there was a message in a log
Could not generate DH keypair
I have fixed this problem by adding BouncyCastle library bcprov-jdk16-1.46.jar
and registering a provider in a map service class
public class MapService {
static {
Security.addProvider(new BouncyCastleProvider());
}
public GeocodeResult geocode() {
}
}
A provider is registered at the first usage of MapService
.
I had to kill multiple instances of MSBuild.exe hanging in process explorer.
Then the website runs OK.
I found in Linux kernel source code that PF_INET and AF_INET are the same. The following code is from file include/linux/socket.h, line 204 of Linux kernel 3.2.21 tree.
/* Protocol families, same as address families. */
...
#define PF_INET AF_INET
Try the following :
String url = "http://www.google.com/search?q=java";
URL urlObj = (URL)new URL(url.trim());
HttpURLConnection httpConn =
(HttpURLConnection)urlObj.openConnection();
httpConn.setRequestMethod("GET");
Integer rescode = httpConn.getResponseCode();
System.out.println(rescode);
Trim() the URL
Try using the SO_REUSEADDR
socket option before binding the socket.
comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Edit:
I see you're still having trouble with this. There is a case where SO_REUSEADDR
won't work. If you try to bind a socket and reconnect to the same destination (with SO_REUSEADDR
enabled), then TIME_WAIT
will still be in effect. It will however allow you to connect to a different host:port.
A couple of solutions come to mind. You can either continue retrying until you can gain a connection again. Or if the client initiates the closing of the socket (not the server), then it should magically work.
What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000
. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:
$ nc -l 4000
...and change socket address to localhost:4000
, it will work and try to read something from nc
-created server.
ServerSocket
and listen on it:ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();
The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)
This one can also be used with less effort I believe (but I am in MVC 5)
@Html.Description(model => model.Story, 20, 50, new { })
If you are using xampp 7.3.9. socket already installed. You can check xampp\php\ext and you will get the php_socket.dll. if you get it go to your xampp control panel open php.ini file and remove (;) from extension=sockets.
Looks like this is a very generic message from iis. in my case we enabled integrated security on web config but forgot to change IIS app pool identity. Things to check -
Note: this may not help every time but this might be one of the reason for above error message.
If using Visual Studio 2010 you can right-click on the project for the service, and select properties
. Then select the Web
tab. Under the Servers
section you can configure the URL. There is also a button to create the virtual directory.
ip = InetAddress.getByAddress(new byte[] {
(byte)192, (byte)168, (byte)0, (byte)102}
);
From the documentation of InetAddress.getByName(String host)
:
The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.
So you can use it.
You could try
document.getElementsByTagName('body')[0].appendChild(i);
Now that won't do you any good if the code is running in the <head>
, and running before the <body>
has even been seen by the browser. If you don't want to mess with "onload" handlers, try moving your <script>
block to the very end of the document instead of the <head>
.
I had this in VS 2012 where the "Section name" had been changed in a project, and I fixed it by deleting "app.config" in the project, then right-clicking on the project in the "Solution Explorer", selecting "Properties", then "Settings", then making a change to one of the settings, saving, and re-building. This created a new app.config with the correct information.
Basically you need following things to make location detector android app
Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.
Using all these resources, you will be able to create an flawless android location detection app.
You will first need to listen for current location of user. You can use any of below libraries to quick start.
This library provide last known location, location updates
With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.
Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.
Google Maps Android API utility library
If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.
Simple, smooth animation for route / polylines on google maps using projections. (WIP)
This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.
This uses telnet behind the scenes, and seems to work fine on mac/linux. It doesn't use netcat because of the differences between the versions on linux/mac, and this works with a default mac install.
$ is_port_open.sh 80 google.com
OPEN
$ is_port_open.sh 8080 google.com
CLOSED
PORT=$1
HOST=$2
TIMEOUT_IN_SEC=${3:-1}
VALUE_IF_OPEN=${4:-"OPEN"}
VALUE_IF_CLOSED=${5:-"CLOSED"}
function eztern()
{
if [ "$1" == "$2" ]
then
echo $3
else
echo $4
fi
}
# cross platform timeout util to support mac mostly
# https://gist.github.com/jaytaylor/6527607
function eztimeout() { perl -e 'alarm shift; exec @ARGV' "$@"; }
function testPort()
{
OPTS=""
# find out if port is open using telnet
# by saving telnet output to temporary file
# and looking for "Escape character" response
# from telnet
FILENAME="/tmp/__port_check_$(uuidgen)"
RESULT=$(eztimeout $TIMEOUT_IN_SEC telnet $HOST $PORT &> $FILENAME; cat $FILENAME | tail -n1)
rm -f $FILENAME;
SUCCESS=$(eztern "$RESULT" "Escape character is '^]'." "$VALUE_IF_OPEN" "$VALUE_IF_CLOSED")
echo "$SUCCESS"
}
testPort
I had exactly the same problem.
The solution was that the file I was trying to access was readonly, as it was copied from a template file that was readonly.
<facepalm />
Reflection is your friend, as has been pointed out. But you need to use the correct method;
Assembly.GetEntryAssembly() //gives you the entrypoint assembly for the process.
Assembly.GetCallingAssembly() // gives you the assembly from which the current method was called.
Assembly.GetExecutingAssembly() // gives you the assembly in which the currently executing code is defined
Assembly.GetAssembly( Type t ) // gives you the assembly in which the specified type is defined.
you can use if() in place of decode() in mySql as follows This query will print all even id row.
mysql> select id, name from employee where id in
-> (select if(id%2=0,id,null) from employee);
Expanding on the answer of Nthalk with Microprofile OpenAPI you can align the return code with your documentation using @APIResponse annotation.
This allows tagging a JAX-RS method like
@GET
@APIResponse(responseCode = "204")
public Resource getResource(ResourceRequest request)
You can parse this standardized annotation with a ContainerResponseFilter
@Provider
public class StatusFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
if (responseContext.getStatus() == 200) {
for (final var annotation : responseContext.getEntityAnnotations()) {
if (annotation instanceof APIResponse response) {
final var rawCode = response.responseCode();
final var statusCode = Integer.parseInt(rawCode);
responseContext.setStatus(statusCode);
}
}
}
}
}
A caveat occurs when you put multiple annotations on your method like
@APIResponse(responseCode = "201", description = "first use case")
@APIResponse(responseCode = "204", description = "because you can")
public Resource getResource(ResourceRequest request)
Here is another gotcha, that took me awhile to see even after reading these posts. I was setting up a script to call my python bin scripts. I was getting the module not callable too.
My zig was that I was doing the following:
from mypackage.bin import myscript
...
myscript(...)
when my zag needed to do the following:
from mypackage.bin.myscript import myscript
...
myscript(...)
In summary, double check your package and module nesting.
What I am trying to do is have a scripts directory that does not have the *.py extension, and still have the 'bin' modules to be in mypackage/bin and these have my *.py extension. I am new to packaging, and trying to follow the standards as I am interpreting them. So, I have at the setup root:
setup.py
scripts/
script1
mypackage/
bin/
script1.py
subpackage1/
subpackage_etc/
If this is not compliant with standard, please let me know.
I messed with this for several hours and tried many different suggestions.
I finally got it to work by doing the following:
Action: Start a program
Program/Script: C:\scriptdir\script.bat
Add arguments (optional) script.bat
Start in (optional): c:\scriptdir
run only when user logged in
run with highest privileges
configure for: Windows Vista, Windows Server 2008
internal static Func<string, string, bool> regKey = delegate (string KeyLocation, string Value)
{
// get registry key with Microsoft.Win32.Registrys
RegistryKey rk = (RegistryKey)Registry.GetValue(KeyLocation, Value, null); // KeyLocation and Value variables from method, null object because no default value is present. Must be casted to RegistryKey because method returns object.
if ((rk) == null) // if the RegistryKey is null which means it does not exist
{
// the key does not exist
return false; // return false because it does not exist
}
// the registry key does exist
return true; // return true because it does exist
};
usage:
// usage:
/* Create Key - while (loading)
{
RegistryKey k;
k = Registry.CurrentUser.CreateSubKey("stuff");
k.SetValue("value", "value");
Thread.Sleep(int.MaxValue);
}; // no need to k.close because exiting control */
if (regKey(@"HKEY_CURRENT_USER\stuff ... ", "value"))
{
// key exists
return;
}
// key does not exist
I haven't needed to turn on anti-alias because it's on by default but I have needed to turn it off. And if it can be turned off it can also be turned on.
ctx.imageSmoothingEnabled = true;
I usually shut it off when I'm working on my canvas rpg so when I zoom in the images don't look blurry.
Also another important note. You have to set android.permission.ACCESS_NETWORK_STATE
in your AndroidManifest.xml for this to work.
_ how could I have found myself the information I needed in the online documentation?
You just have to read the documentation the the classes properly enough and you'll find all answers you are looking for. Check out the documentation on ConnectivityManager. The description tells you what to do.
Check if there is any conflict in your IIS authentication. i.e. you enable the anonymous authentication and ASP.NET impersonation both might cause the error also.
Here goes mix of weekens's and Vovodroid's solutions.
It is more correct than Vovodroid's solution and more complete than weekens's solution.
try {
InputStream inputStream = res.openRawResource(resId);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return result.toString();
} finally {
reader.close();
}
} finally {
inputStream.close();
}
} catch (IOException e) {
// process exception
}
I tried to make the code more readable. This works for numbers within integer range
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;
public class Solution2 {
static Map<Integer, String> numberMap = new HashMap<Integer, String>();
static Map<Integer, String> tensMap = new HashMap<Integer, String>();
static Map<Integer, String> exponentsMap = new HashMap<Integer, String>();
public static void main(String[] args) {
LinkedList<String> wordList = new LinkedList<String>();
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
scan.close();
exponentsMap.put(3, "thousand");
exponentsMap.put(6, "million");
exponentsMap.put(9, "billion");
tensMap.put(2, "twenty");
tensMap.put(3, "thirty");
tensMap.put(4, "forty");
tensMap.put(5, "fifty");
tensMap.put(6, "sixty");
tensMap.put(7, "seventy");
tensMap.put(8, "eighty");
tensMap.put(9, "ninety");
numberMap.put(1, "one");
numberMap.put(2, "two");
numberMap.put(3, "three");
numberMap.put(4, "four");
numberMap.put(5, "five");
numberMap.put(6, "six");
numberMap.put(7, "seven");
numberMap.put(8, "eight");
numberMap.put(9, "nine");
numberMap.put(10, "ten");
numberMap.put(11, "eleven");
numberMap.put(12, "twelve");
numberMap.put(13, "thirteen");
numberMap.put(14, "fourteen");
numberMap.put(15, "fifteen");
numberMap.put(16, "sixteen");
numberMap.put(17, "seventeen");
numberMap.put(18, "eighteen");
numberMap.put(19, "nineteen");
int temp = input;
int exponentCounter =0;
while(temp>0) {
// words from 1 to 99
addLastTwo(temp%100,wordList);
temp=temp/100;
// add hundreds before exponents
if(temp!=0) {
wordList.addFirst("hundred");
wordList.addFirst(numberMap.getOrDefault(temp%10,""));
temp = temp/10;
}
// words for exponents
if(temp!=0) {
exponentCounter+=3;
wordList.addFirst(exponentsMap.getOrDefault(exponentCounter,""));
}
}
wordList.stream().filter(word -> !word.contentEquals("")).forEach(word -> System.out.print(word + " "));
}
private static void addLastTwo(int num, LinkedList<String> wordList) {
if (num > 19) {
wordList.addFirst(numberMap.getOrDefault(num % 10,""));
wordList.addFirst(tensMap.getOrDefault(num / 10,""));
} else {
wordList.addFirst(numberMap.getOrDefault(num,""));
}
}
}
Ping for the google server or any other server
public boolean isConecctedToInternet() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
return false;
}
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
}
This can be sought of a temporary solution.
Unicode has accepted U+20B9
as Indian rupee symbol soon all systems will update themselves
Here is yet another way without Invoke-Expression
but with two variables
(command:string and parameters:array). It works fine for me. Assume
7z.exe
is in the system path.
$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'
& $cmd $prm
If the command is known (7z.exe) and only parameters are variable then this will do
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'
& 7z.exe $prm
BTW, Invoke-Expression
with one parameter works for me, too, e.g. this works
$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'
Invoke-Expression $cmd
P.S. I usually prefer the way with a parameter array because it is easier to
compose programmatically than to build an expression for Invoke-Expression
.
this function shows how to create a triangle from bitmap. That is, create triangular shaped cropped image. Try the code below or download demo example
public static Bitmap getTriangleBitmap(Bitmap bitmap, int radius) {
Bitmap finalBitmap;
if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
false);
else
finalBitmap = bitmap;
Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Paint paint = new Paint();
final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
finalBitmap.getHeight());
Point point1_draw = new Point(75, 0);
Point point2_draw = new Point(0, 180);
Point point3_draw = new Point(180, 180);
Path path = new Path();
path.moveTo(point1_draw.x, point1_draw.y);
path.lineTo(point2_draw.x, point2_draw.y);
path.lineTo(point3_draw.x, point3_draw.y);
path.lineTo(point1_draw.x, point1_draw.y);
path.close();
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
canvas.drawPath(path, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(finalBitmap, rect, rect, paint);
return output;
}
The function above returns an triangular image drawn on canvas. Read more
Try Project Euler:
Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.
The problem is:
Add all the natural numbers below 1000 that are multiples of 3 or 5.
This question will probably introduce you to Python for-loops and the range() builtin function in the least. It might lead you to discover list comprehensions, or generator expressions and the sum() builtin function.
It's not that easy since a machine inside a LAN usually doesn't care about the external IP of its router to the internet.. it simply doesn't need it!
I would suggest you to exploit this by opening a site like http://www.whatismyip.com/ and getting the IP number by parsing the html results.. it shouldn't be that hard!
Set the socket non-blocking, and use select()
(which takes a timeout parameter). If a non-blocking socket is trying to connect, then select()
will indicate that the socket is writeable when the connect()
finishes (either successfully or unsuccessfully). You then use getsockopt()
to determine the outcome of the connect()
:
int main(int argc, char **argv) {
u_short port; /* user specified port number */
char *addr; /* will be a pointer to the address */
struct sockaddr_in address; /* the libc network address data structure */
short int sock = -1; /* file descriptor for the network socket */
fd_set fdset;
struct timeval tv;
if (argc != 3) {
fprintf(stderr, "Usage %s <port_num> <address>\n", argv[0]);
return EXIT_FAILURE;
}
port = atoi(argv[1]);
addr = argv[2];
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(addr); /* assign the address */
address.sin_port = htons(port); /* translate int2port num */
sock = socket(AF_INET, SOCK_STREAM, 0);
fcntl(sock, F_SETFL, O_NONBLOCK);
connect(sock, (struct sockaddr *)&address, sizeof(address));
FD_ZERO(&fdset);
FD_SET(sock, &fdset);
tv.tv_sec = 10; /* 10 second timeout */
tv.tv_usec = 0;
if (select(sock + 1, NULL, &fdset, NULL, &tv) == 1)
{
int so_error;
socklen_t len = sizeof so_error;
getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (so_error == 0) {
printf("%s:%d is open\n", addr, port);
}
}
close(sock);
return 0;
}
It would seem overkill but Spring Forms handles this elegantly. That is of course if you are already using Spring MVC and you want to take advantage of the Spring Forms feature.
// jsp form
<form:select path="friendlyNumber" items="${friendlyNumberItems}" />
// the command class
public class NumberCmd {
private String[] friendlyNumber;
}
// in your Spring MVC controller submit method
@RequestMapping(method=RequestMethod.POST)
public String manageOrders(@ModelAttribute("nbrCmd") NumberCmd nbrCmd){
String[] selectedNumbers = nbrCmd.getFriendlyNumber();
}
You can use this code to retrieve values from multiple select combo box
HTML:
<form action="c3.php" method="post">
<select name="ary[]" multiple="multiple">
<option value="Option 1" >Option 1</option>
<option value="Option 2">Option 2</option>
<option value="Option 3">Option 3</option>
<option value="Option 4">Option 4</option>
<option value="Option 5">Option 5</option>
</select>
<input type="submit">
</form>
PHP:
<?php
$values = $_POST['ary'];
foreach ($values as $a){
echo $a;
}
?>
ConfigurationSettings.AppSettings is deprecated, see here:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationsettings.appsettings.aspx
That said, it should still work.
Just a suggestion, but have you confirmed that your application configuration is the one your executable is using?
Try attaching a debugger and checking the following value:
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
And then opening the configuration file and verifying the section is there as you expected.
Apparently there were two web.config files in my solution. I am using MVC4 and there was another config file under Views and i was making the change in the wrong file. Fixed there helped me.
But you can always change the default redirect/route in the global.asax file.
try {
LdapContext ctx = new InitialLdapContext(env, null);
ctx.setRequestControls(null);
NamingEnumeration<?> namingEnum = ctx.search("ou=people,dc=example,dc=com", "(objectclass=user)", getSimpleSearchControls());
while (namingEnum.hasMore ()) {
SearchResult result = (SearchResult) namingEnum.next ();
Attributes attrs = result.getAttributes ();
System.out.println(attrs.get("cn"));
}
namingEnum.close();
} catch (Exception e) {
e.printStackTrace();
}
private SearchControls getSimpleSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(30000);
//String[] attrIDs = {"objectGUID"};
//searchControls.setReturningAttributes(attrIDs);
return searchControls;
}
I got similar error when i run legacy application in Visual studio 2013 iis express and solved the issue by following steps 1.Navigate to "Documents\IISExpress\config" 2.Open "applicationhost.config" using notepad or any preferred editor 3.scroll down and find for section name="anonymousAuthentication" under 4. Update overrideModeDefault="Deny" to "Allow" 5. save the config file 6. Run the legacy application and worked fine for me.
You actually can use an inet function. Observe.
main.c:
#include <arpa/inet.h>
main() {
uint32_t ip = 2110443574;
struct in_addr ip_addr;
ip_addr.s_addr = ip;
printf("The IP address is %s\n", inet_ntoa(ip_addr));
}
The results of gcc main.c -ansi; ./a.out
is
The IP address is 54.208.202.125
Note that a commenter said this does not work on Windows.
As long as you go into the IIS configuration and change the default location from %SystemDrive%\InetPub to %SystemDrive%\www for each of the services (web, ftp) there shouldn't be any problems. Of course, you can't protect against other applications that might install stuff into that directory by default, instead of checking the configuration.
My recommendation? Don't change it -- it's not that hard to live with, and it reduces the confusion level for the next person who has to administrate the machine.
You need arguments like AF_UNIX or AF_INET to specify which type of socket addressing you would be using to implement IPC socket communication. AF stands for Address Family.
As in BSD standard Socket (adopted in Python socket module) addresses are represented as follows:
A single string is used for the AF_UNIX/AF_LOCAL address family. This option is used for IPC on local machines where no IP address is required.
A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in Internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer. Used to communicate between processes over the Internet.
AF_UNIX , AF_INET6 , AF_NETLINK , AF_TIPC , AF_CAN , AF_BLUETOOTH , AF_PACKET , AF_RDS are other option which could be used instead of AF_INET.
This thread about the differences between AF_INET and PF_INET might also be useful.
Found at and modified (!) from this link :
In your manifest file add at least:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You probably already have the INTERNET permission if you are accessing it. Then a boolean function that allows to test for connectivity is:
private boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
Log.v(TAG, "Internet Connection Not Present");
return false;
}
}
If you're running cPanel/WHM, make sure that IP is whitelisted in the firewall. You will als need to add that IP to the remote SQL IP list in the cPanel account you're trying to connect to.
For Swift: Here is a simple extension to UIImage:
//ImageRotation.swift
import UIKit
extension UIImage {
public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage {
let radiansToDegrees: (CGFloat) -> CGFloat = {
return $0 * (180.0 / CGFloat(M_PI))
}
let degreesToRadians: (CGFloat) -> CGFloat = {
return $0 / 180.0 * CGFloat(M_PI)
}
// calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size))
let t = CGAffineTransformMakeRotation(degreesToRadians(degrees));
rotatedViewBox.transform = t
let rotatedSize = rotatedViewBox.frame.size
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap = UIGraphicsGetCurrentContext()
// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width / 2.0, rotatedSize.height / 2.0);
// // Rotate the image context
CGContextRotateCTM(bitmap, degreesToRadians(degrees));
// Now, draw the rotated/scaled image into the context
var yFlip: CGFloat
if(flip){
yFlip = CGFloat(-1.0)
} else {
yFlip = CGFloat(1.0)
}
CGContextScaleCTM(bitmap, yFlip, -1.0)
CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
(Source)
Use it with:
rotatedPhoto = rotatedPhoto?.imageRotatedByDegrees(90, flip: false)
The former will rotate an image and flip it if flip is set to true.
In the menu, go to RUN > services.msc
and hit enter to get the services window and check for the IIS ADMIN service. If it is not present, then reinstall IIS using your windows CD.
Try this:
Create A Macro with the following thing inside:
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select
That particular macro will copy the current cell (place your cursor in the VOL cell you wish to copy) down one row and then copy the CAP cell also.
This is only a single loop so you can automate copying VOL and CAP of where your current active cell (where your cursor is) to down 1 row.
Just put it inside a For loop statement to do it x number of times. like:
For i = 1 to 100 'Do this 100 times
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select
Next i
Can you try this without
contentType:application/x-www-form-urlencoded
The error message is quite clear: you have a configuration element in a web.config file in a subfolder of your web app that is not allowed at that level - OR you forgot to configure your web application as IIS application.
Example: you try to override application level settings like forms authentication parameters in a web.config in a subfolder of your application
ASP.Net applications come pre-wired with a handlers section in the web.config. By default, this is set to readonly within feature delegation within IIS. Take a look in IIS Manager
1.Go to IIS Manager and click Server Name
2.Go to the section Management and click Feature Delegation.
3.Select the Handler Mappings which is supposed to set as readonly.
4.Change the value to read/write and now you can get resolved the issue
What does
$ git config --get-regexp '^(remote|branch)\.'
returns (executed within your git repository) ?
Origin is just a default naming convention for referring to a remote Git repository.
If it does not refer to GitHub (but rather a path to your teammate repository, path which may no longer be valid or available), just add another origin, like in this Bloggitation entry
$ git remote add origin2 [email protected]:myLogin/myProject.git
$ git push origin2 master
(I would actually use the name 'github' rather than 'origin' or 'origin2')
Permission denied (publickey).
fatal: The remote end hung up unexpectedly
Check if your gitHub identity is correctly declared in your local Git repository, as mentioned in the GitHub Help guide. (both user.name and github.name -- and github.token)
Then, stonean blog suggests (as does Marcio Garcia):
$ cd ~/.ssh
$ ssh-add id_rsa
Aral Balkan adds: create a config file
The solution was to create a config file under ~/.ssh/ as outlined at the bottom of the OS X section of this page.
Here's the file I added, as per the instructions on the page, and my pushes started working again:
Host github.com
User git
Port 22
Hostname github.com
IdentityFile ~/.ssh/id_rsa
TCPKeepAlive yes
IdentitiesOnly yes
You can also post the result of
ssh -v [email protected]
to have more information as to why GitHub ssh connection rejects you.
Check also you did enter correctly your public key (it needs to end with '==
').
Do not paste your private key, but your public one. A public key would look something like:
ssh-rsa AAAAB3<big string here>== [email protected]
(Note: did you use a passphrase for your ssh keys ? It would be easier without a passphrase)
Check also the url used when pushing ([email protected]/...
, not git://github.com/...
)
Check that you do have a SSH Agent to use and cache your key.
Try this:
$ ssh -i path/to/public/key [email protected]
If that works, then it means your key is not being sent to GitHub by your ssh client.
Try setting the timeout value in your web service proxy class:
WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds
Where are you allocating memory for your buffer
? The line where you invoke bzero
invokes undefined behavior since buffer does not point to any valid region of memory.
char *buffer = new char[ BUFFER_SIZE ];
// do processing
// don't forget to release
delete[] buffer;
To get the currently logged in user:
System.getProperty("user.name");
To get the host name of the machine:
InetAddress.getLocalHost().getHostName();
To answer the last part of your question, the Java API says that getHostName() will return
the host name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.
I ran into this same issue trying to deploy my MVC3 Razor web application on GoDaddy shared hosting. There are some additional .dlls that need to be referenced. Details here: http://paulmason.biz/?p=108
Basically you need to add references to the following in addition to the ones listed in @Haacked's post and set them to deploy locally as described.
If you're looking to put line breaks into the tooltip that appears on mouseover, there's no reliable crossbrowser way to do that. You'd have to fall back to one of the many Javascript tooltip code samples
I got around the issue by using a convert on the "?", so my code looks like convert(char(50),?) and that got rid of the truncation error.
They left out this behaviour by design to avoid when it was not used by will but caused problems.
It can be used only if there is no statement in the case part, like:
switch (whatever)
{
case 1:
case 2:
case 3: boo; break;
}
There is another way to pristine form that is by sending form into the controller. For example:-
In view:-
<form name="myForm" ng-submit="addUser(myForm)" novalidate>
<input type="text" ng-mode="user.name"/>
<span style="color:red" ng-show="myForm.name.$dirty && myForm.name.$invalid">
<span ng-show="myForm.name.$error.required">Name is required.</span>
</span>
<button ng-disabled="myForm.$invalid">Add User</button>
</form>
In Controller:-
$scope.addUser = function(myForm) {
myForm.$setPristine();
};
I prefer to put the variable on the inside to give an extra hint that the code is validating my variable is between a range values
if (500 < size && size < 600) { doStuff(); }
In many cases an element must be positioned for z-index
to work.
Indeed, applying position: relative
to the elements in the question would likely solve the problem (but there's not enough code provided to know for sure).
Actually, position: fixed
, position: absolute
and position: sticky
will also enable z-index
, but those values also change the layout. With position: relative
the layout isn't disturbed.
Essentially, as long as the element isn't position: static
(the default setting) it is considered positioned and z-index
will work.
Many answers to "Why isn't z-index working?" questions assert that z-index
only works on positioned elements. As of CSS3, this is no longer true.
Elements that are flex items or grid items can use z-index
even when position
is static
.
From the specs:
Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.5.4. Z-axis Ordering: the
z-index
propertyThe painting order of grid items is exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.
Here's a demonstration of z-index
working on non-positioned flex items: https://jsfiddle.net/m0wddwxs/
Once you have markers on the map, you can retrieve the Lat/Long coordinates through the API and use this to set the map's center. You'll first just need to determine which marker you wish to center on - I'll leave that up to you.
// "marker" refers to the Marker object you wish to center on
var latLng = marker.getPosition(); // returns LatLng object
map.setCenter(latLng); // setCenter takes a LatLng object
Info windows are separate objects which are typically bound to a marker, so to open the info window you might do something like this (however it will depend on your code):
var infoWindow = marker.infoWindow; // retrieve the InfoWindow object
infoWindow.open(map); // Trigger the "open()" method
Hope this helps.
This will output the date in YYYY-MM-DD format:
let date = new Date();
date = date.toISOString().slice(0,10);
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
"I'd like to paste yanked text into Vim command line."
While the top voted answer is very complete, I prefer editing the command history.
In normal mode, type: q:
. This will give you a list of recent commands, editable and searchable with normal vim commands. You'll start on a blank command line at the bottom.
For the exact thing that the article asks, pasting a yanked line (or yanked anything) into a command line, yank your text and then: q:p
(get into command history edit mode, and then (p)ut your yanked text into a new command line. Edit at will, enter to execute.
To get out of command history mode, it's the opposite. In normal mode in command history, type: :q
+ enter
As it was mentioned, there is no direct equivalent, but very close approximation could be created with Java bytecode modifications (for both async/await-like instructions and underlying continuations implementation).
I'm working right now on a project that implements async/await on top of JavaFlow continuation library, please check https://github.com/vsilaev/java-async-await
No Maven mojo is created yet, but you may run examples with supplied Java agent. Here is how async/await code looks like:
public class AsyncAwaitNioFileChannelDemo {
public static void main(final String[] argv) throws Exception {
...
final AsyncAwaitNioFileChannelDemo demo = new AsyncAwaitNioFileChannelDemo();
final CompletionStage<String> result = demo.processFile("./.project");
System.out.println("Returned to caller " + LocalTime.now());
...
}
public @async CompletionStage<String> processFile(final String fileName) throws IOException {
final Path path = Paths.get(new File(fileName).toURI());
try (
final AsyncFileChannel file = new AsyncFileChannel(
path, Collections.singleton(StandardOpenOption.READ), null
);
final FileLock lock = await(file.lockAll(true))
) {
System.out.println("In process, shared lock: " + lock);
final ByteBuffer buffer = ByteBuffer.allocateDirect((int)file.size());
await( file.read(buffer, 0L) );
System.out.println("In process, bytes read: " + buffer);
buffer.rewind();
final String result = processBytes(buffer);
return asyncResult(result);
} catch (final IOException ex) {
ex.printStackTrace(System.out);
throw ex;
}
}
@async is the annotation that flags a method as asynchronously executable, await() is a function that waits on CompletableFuture using continuations and a call to "return asyncResult(someValue)" is what finalizes associated CompletableFuture/Continuation
As with C#, control flow is preserved and exception handling may be done in regular manner (try/catch like in sequentially executed code)
when reimporting your keys from the old keyring, you need to specify the command:
gpg --allow-secret-key-import --import <keyring>
otherwise it will only import the public keys, not the private keys.
Initialize all your array elements to null first, then look for the null to find the empty slot
It's a mechanism to invoke an API in an asynchrounous way. The sequence is the following
So you can invoke the api and tell your user the request is "processing" or "acquired" for example, and then update the status when you receive the response from the api.
Hope it makes sense. -G
This solution has left aligned text and button on the far right.
If anyone is looking for a material design answer:
<div layout="column" layout-align="start start">
<div layout="row" style="width:100%">
<div flex="grow">Left Aligned text</div>
<md-button aria-label="help" ng-click="showHelpDialog()">
<md-icon md-svg-icon="help"></md-icon>
</md-button>
</div>
</div>
TypeScript supports decorators, and using that feature plus a little library called typescript-mix you can use mixins to have multiple inheritance with just a couple of lines
// The following line is only for intellisense to work
interface Shopperholic extends Buyer, Transportable {}
class Shopperholic {
// The following line is where we "extend" from other 2 classes
@use( Buyer, Transportable ) this
price = 2000;
}
Path.GetDirectoryName()
... but you need to know that the path you are passing to it does contain a file name; it simply removes the final bit from the path, whether it is a file name or directory name (it actually has no idea which).
You could validate first by testing File.Exists()
and/or Directory.Exists()
on your path first to see if you need to call Path.GetDirectoryName
$('#div1').scrollTop($('#div1')[0].scrollHeight);
Or animated:
$("#div1").animate({ scrollTop: $('#div1')[0].scrollHeight}, 1000);
What you want to do is called "serialization". There are several ways of doing it, but if you don't need anything fancy I think using the standard Java object serialization would do just fine.
Perhaps you could use something like this?
package com.example;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Serializer {
public static byte[] serialize(Object obj) throws IOException {
try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
try(ObjectOutputStream o = new ObjectOutputStream(b)){
o.writeObject(obj);
}
return b.toByteArray();
}
}
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
try(ObjectInputStream o = new ObjectInputStream(b)){
return o.readObject();
}
}
}
}
There are several improvements to this that can be done. Not in the least the fact that you can only read/write one object per byte array, which might or might not be what you want.
Note that "Only objects that support the java.io.Serializable
interface can be written to streams" (see java.io.ObjectOutputStream
).
Since you might run into it, the continuous allocation and resizing of the java.io.ByteArrayOutputStream
might turn out to be quite the bottle neck. Depending on your threading model you might want to consider reusing some of the objects.
For serialization of objects that do not implement the Serializable
interface you either need to write your own serializer, for example using the read*/write* methods of java.io.DataOutputStream
and the get*/put* methods of java.nio.ByteBuffer
perhaps together with reflection, or pull in a third party dependency.
This site has a list and performance comparison of some serialization frameworks. Looking at the APIs it seems Kryo might fit what you need.
Therefore, before starting '$ sqlplus' on OS, run the followings:
On Windows
set NLS_LANG=AMERICAN_AMERICA.UTF8
On Unix (Solaris and Linux, centos etc)
export NLS_LANG=AMERICAN_AMERICA.UTF8
It would also be advisable to set env variable in your '.bash_profile' [on start up script]
This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.
just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.
Your password seems to be incorrect. Recheck your credentials.
I find this to be the most straightforward and working:
df = pd.DataFrame({
'one thing':[1,2,3,4],
'second thing':[0.1,0.2,1,2],
'other thing':['a','e','i','o']})
df = df[['one thing','second thing', 'other thing']]
You can use the SYS_GUID() function to generate a GUID in your insert statement:
insert into mytable (guid_col, data) values (sys_guid(), 'xxx');
The preferred datatype for storing GUIDs is RAW(16).
As Gopinath answer:
select sys_guid() from dual
union all
select sys_guid() from dual
union all
select sys_guid() from dual
You get
88FDC68C75DDF955E040449808B55601
88FDC68C75DEF955E040449808B55601
88FDC68C75DFF955E040449808B55601
As Tony Andrews says, differs only at one character
88FDC68C75DDF955E040449808B55601
88FDC68C75DEF955E040449808B55601
88FDC68C75DFF955E040449808B55601
Maybe useful: http://feuerthoughts.blogspot.com/2006/02/watch-out-for-sequential-oracle-guids.html
Why not use ES6?
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
const [, ...rest] = myarray;_x000D_
console.log(rest)
_x000D_
For Node 10.3+, here is a for-await solution:
#!/usr/bin/env node
const FS = require('fs');
const Util = require('util');
const readDir = Util.promisify(FS.readdir);
const Path = require('path');
async function* readDirR(path) {
const entries = await readDir(path,{withFileTypes:true});
for(let entry of entries) {
const fullPath = Path.join(path,entry.name);
if(entry.isDirectory()) {
yield* readDirR(fullPath);
} else {
yield fullPath;
}
}
}
async function main() {
const start = process.hrtime.bigint();
for await(const file of readDirR('/mnt/home/media/Unsorted')) {
console.log(file);
}
console.log((process.hrtime.bigint()-start)/1000000n);
}
main().catch(err => {
console.error(err);
});
The benefit of this solution is that you can start processing the results immediately; e.g. it takes 12 seconds to read all the files in my media directory, but if I do it this way I can get the first result within a few milliseconds.
You may also want to consider the possibility of using SWT (another Java GUI library). Pros and cons of each are listed at:
Just for reference if anyone is still struggling with mongorestore.
You have to run monogorestore in terminal/command prompt and not in mongo console.
$ mongorestore -d db_name /path_to_mongo_dump/
for more details you can visit official documentations
https://docs.mongodb.com/manual/reference/program/mongorestore/
You can use:
<input type="number" step="any" min="0" max="100" value="22.33">
Short solution:
const query = {}
const projection = {}
const options = { sort: { id: 1 }, limit: 2, skip: 10 }
Room.find(query, projection, options).exec(function(err, docs) { ... });
The simplest way I found is using @JsonFormat.Shape.OBJECT annotation for the enum.
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum MyEnum{
....
}
Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate
now has second parameter values
, which is being used for new record, but not for search
$user = User::firstOrCreate([
'email' => '[email protected]'
], [
'firstName' => 'Taylor',
'lastName' => 'Otwell'
]);
I was trying to set the log_statement
in some postgres config file but in fact the file was not read by our postgres.
I confirmed that using the request :
select *
from pg_settings
[...]
log_statement none # That was not the value i was expected for !!!
I use this way https://stackoverflow.com/a/41912295/2294168
command: postgres -c config_file=/etc/postgresql.conf
Since newcol
is the ID of the radio button, You can simply use it as below.
$("#"+newcol).attr('checked',true);
Use the updated version of Firebase and avoid extras. This is enough (but if you need to use storage space or .. you should add them too)
//FIREBASE
implementation 'com.google.firebase:firebase-core:17.2.0'
implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
//ADMob
implementation 'com.google.android.gms:play-services-ads:18.2.0'
//PUSH NOTIFICATION
implementation 'com.google.firebase:firebase-messaging:20.0.0'
implementation 'com.google.firebase:firebase-core:17.2.0'
and update the google-services :
classpath 'com.google.gms:google-services:4.3.2'
Why not just using simple css :
<router-outlet></router-outlet>
<div class="loading"></div>
And in your styles :
div.loading{
height: 100px;
background-color: red;
display: none;
}
router-outlet + div.loading{
display: block;
}
Or even we can do this for the first answer:
<router-outlet></router-outlet>
<spinner-component></spinner-component>
And then simply just
spinner-component{
display:none;
}
router-outlet + spinner-component{
display: block;
}
The trick here is, the new routes and components will always appear after router-outlet , so with a simple css selector we can show and hide the loading.
Since value is the last entry, you can do:
metrics.sort_by(&:last)
Calculating square roots by Newton's method is horrendously fast ... provided that the starting value is reasonable. However there is no reasonable starting value, and in practice we end with bisection and log(2^64) behaviour.
To be really fast we need a fast way to get at a reasonable starting value, and that means we need to descend into machine language.
If a processor provides an instruction like POPCNT in the Pentium, that counts the leading zeroes we can use that to have a starting value with half the significant bits. With care we can find a a fixed number of Newton steps that will always suffice.
(Thus foregoing the need to loop and have very fast execution.)
A second solution is going via the floating point facility, which may have a fast sqrt calculation (like the i87 coprocessor.) Even an excursion via exp() and log() may be faster than Newton degenerated into a binary search. There is a tricky aspect to this, a processor dependant analysis of what and if refinement afterwards is necessary.
A third solution solves a slightly different problem, but is well worth mentionning because the situation is described in the question. If you want to calculate a great many square roots for numbers that differ slightly, you can use Newton iteration, if you never reinitialise the starting value, but just leave it where the previous calculation left off. I've used this with success in at least one Euler problem.
I had the same issue, but when I ran the following command, it was ok:
php artisan config:cache
I used a few options mentioned above :
del self.left
or setting value to None using
self.left = None
It's important to know the differences and put a few exception handlers in place when you use set the value to None. If you're printing the value of the conditional statements using a template, say,
print("The value of the variable is {}".format(self.left))
you might see the value of the variable printing "The value of the variable is None". Thus, you'd have to put a few exception handlers there :
if self.left:
#Then only print stuff
The above command will only print values if self.left is not None
There is a hidden cost in removing elements from an ArrayList. Each time you delete an element, you need to move the elements to fill the "hole". On average, this will take N / 2
assignments for a list with N elements.
So removing M elements from an N element ArrayList is O(M * N)
on average. An O(N) solution involves creating a new list. For example.
List data = ...;
List newData = new ArrayList(data.size());
for (Iterator i = data.iterator(); i.hasNext(); ) {
Object element = i.next();
if ((...)) {
newData.add(element);
}
}
If N is large, my guess is that this approach will be faster than the remove
approach for values of M as small as 3 or 4.
But it is important to create newList
large enough to hold all elements in list
to avoid copying the backing array when it is expanded.
Custom zoom view in Kotlin
import android.content.Context
import android.graphics.Matrix
import android.graphics.PointF
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener
import androidx.appcompat.widget.AppCompatImageView
class ZoomImageview : AppCompatImageView {
var matri: Matrix? = null
var mode = NONE
// Remember some things for zooming
var last = PointF()
var start = PointF()
var minScale = 1f
var maxScale = 3f
lateinit var m: FloatArray
var viewWidth = 0
var viewHeight = 0
var saveScale = 1f
protected var origWidth = 0f
protected var origHeight = 0f
var oldMeasuredWidth = 0
var oldMeasuredHeight = 0
var mScaleDetector: ScaleGestureDetector? = null
var contex: Context? = null
constructor(context: Context) : super(context) {
sharedConstructing(context)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
sharedConstructing(context)
}
private fun sharedConstructing(context: Context) {
super.setClickable(true)
this.contex= context
mScaleDetector = ScaleGestureDetector(context, ScaleListener())
matri = Matrix()
m = FloatArray(9)
imageMatrix = matri
scaleType = ScaleType.MATRIX
setOnTouchListener { v, event ->
mScaleDetector!!.onTouchEvent(event)
val curr = PointF(event.x, event.y)
when (event.action) {
MotionEvent.ACTION_DOWN -> {
last.set(curr)
start.set(last)
mode = DRAG
}
MotionEvent.ACTION_MOVE -> if (mode == DRAG) {
val deltaX = curr.x - last.x
val deltaY = curr.y - last.y
val fixTransX = getFixDragTrans(deltaX, viewWidth.toFloat(), origWidth * saveScale)
val fixTransY = getFixDragTrans(deltaY, viewHeight.toFloat(), origHeight * saveScale)
matri!!.postTranslate(fixTransX, fixTransY)
fixTrans()
last[curr.x] = curr.y
}
MotionEvent.ACTION_UP -> {
mode = NONE
val xDiff = Math.abs(curr.x - start.x).toInt()
val yDiff = Math.abs(curr.y - start.y).toInt()
if (xDiff < CLICK && yDiff < CLICK) performClick()
}
MotionEvent.ACTION_POINTER_UP -> mode = NONE
}
imageMatrix = matri
invalidate()
true // indicate event was handled
}
}
fun setMaxZoom(x: Float) {
maxScale = x
}
private inner class ScaleListener : SimpleOnScaleGestureListener() {
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
mode = ZOOM
return true
}
override fun onScale(detector: ScaleGestureDetector): Boolean {
var mScaleFactor = detector.scaleFactor
val origScale = saveScale
saveScale *= mScaleFactor
if (saveScale > maxScale) {
saveScale = maxScale
mScaleFactor = maxScale / origScale
} else if (saveScale < minScale) {
saveScale = minScale
mScaleFactor = minScale / origScale
}
if (origWidth * saveScale <= viewWidth || origHeight * saveScale <= viewHeight) matri!!.postScale(mScaleFactor, mScaleFactor, viewWidth / 2.toFloat(), viewHeight / 2.toFloat()) else matri!!.postScale(mScaleFactor, mScaleFactor, detector.focusX, detector.focusY)
fixTrans()
return true
}
}
fun fixTrans() {
matri!!.getValues(m)
val transX = m[Matrix.MTRANS_X]
val transY = m[Matrix.MTRANS_Y]
val fixTransX = getFixTrans(transX, viewWidth.toFloat(), origWidth * saveScale)
val fixTransY = getFixTrans(transY, viewHeight.toFloat(), origHeight * saveScale)
if (fixTransX != 0f || fixTransY != 0f) matri!!.postTranslate(fixTransX, fixTransY)
}
fun getFixTrans(trans: Float, viewSize: Float, contentSize: Float): Float {
val minTrans: Float
val maxTrans: Float
if (contentSize <= viewSize) {
minTrans = 0f
maxTrans = viewSize - contentSize
} else {
minTrans = viewSize - contentSize
maxTrans = 0f
}
if (trans < minTrans) return -trans + minTrans
if (trans > maxTrans) return -trans + maxTrans
return 0f
}
fun getFixDragTrans(delta: Float, viewSize: Float, contentSize: Float): Float {
if (contentSize <= viewSize) {
return 0f
} else {
return delta
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
viewWidth = MeasureSpec.getSize(widthMeasureSpec)
viewHeight = MeasureSpec.getSize(heightMeasureSpec)
//
// Rescales image on rotation
//
if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight || viewWidth == 0 || viewHeight == 0) return
oldMeasuredHeight = viewHeight
oldMeasuredWidth = viewWidth
if (saveScale == 1f) {
//Fit to screen.
val scale: Float
val drawable = drawable
if (drawable == null || drawable.intrinsicWidth == 0 || drawable.intrinsicHeight == 0) return
val bmWidth = drawable.intrinsicWidth
val bmHeight = drawable.intrinsicHeight
Log.d("bmSize", "bmWidth: $bmWidth bmHeight : $bmHeight")
val scaleX = viewWidth.toFloat() / bmWidth.toFloat()
val scaleY = viewHeight.toFloat() / bmHeight.toFloat()
scale = Math.min(scaleX, scaleY)
matri!!.setScale(scale, scale)
// Center the image
var redundantYSpace = viewHeight.toFloat() - scale * bmHeight.toFloat()
var redundantXSpace = viewWidth.toFloat() - scale * bmWidth.toFloat()
redundantYSpace /= 2.toFloat()
redundantXSpace /= 2.toFloat()
matri!!.postTranslate(redundantXSpace, redundantYSpace)
origWidth = viewWidth - 2 * redundantXSpace
origHeight = viewHeight - 2 * redundantYSpace
imageMatrix = matri
}
fixTrans()
}
companion object {
// We can be in one of these 3 states
const val NONE = 0
const val DRAG = 1
const val ZOOM = 2
const val CLICK = 3
}
}
You can do this as well, hopeit helps
<span style="color:black"><i class="glyphicon glyphicon-music"></i></span>
For Django 2:
from django.utils.deprecation import MiddlewareMixin
class DisableCSRF(MiddlewareMixin):
def process_request(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
That middleware must be added to settings.MIDDLEWARE
when appropriate (in your test settings for example).
Note: the setting isn't not called MIDDLEWARE_CLASSES
anymore.
The selected answer is correct for iOS 6 and below.
In iOS 7, sizeWithFont:constrainedToSize:lineBreakMode:
has been deprecated. It is now recommended you use boundingRectWithSize:options:attributes:context:
.
CGRect expectedLabelSize = [yourString boundingRectWithSize:sizeOfRect
options:<NSStringDrawingOptions>
attributes:@{
NSFontAttributeName: yourString.font
AnyOtherAttributes: valuesForAttributes
}
context:(NSStringDrawingContext *)];
Note that the return value is a CGRect
not a CGSize
. Hopefully that'll be of some assistance to people using it in iOS 7.
If you need a more specific text alignment than what adding spaces to the left of the text provides, you can always add a second blank label of exactly how much of an indent you need.
I've got buttons with text aligned left with an indent of 10px and needed a label below to look in line. It gave the label with text and left alignment and put it at x=10 and then made a small second label of the same background color with a width = 10, and lined it up next to the real label.
Minimal code and looks good. Just makes AutoLayout a little more of a hassle to get everything working.
Someone pointed me to args4j lately which is annotation based. I really like it!
//How about byte-ing it?
Number.prototype.isInt= function(){
return this== this>> 0;
}
I always feel kind of bad for bit operators in javascript-
they hardly get any exercise.
If the file is for opening you could use one of the following techniques:
with open('somefile', 'xt') as f: #Using the x-flag, Python3.3 and above
f.write('Hello\n')
if not os.path.exists('somefile'):
with open('somefile', 'wt') as f:
f.write("Hello\n")
else:
print('File already exists!')
UPDATE
Just to avoid confusion and based on the answers I got, current answer finds either a file or a directory with the given name.
In many cases the purpose of a Null value is to serve for a data value that was not present in a previous version of your application.
So say you have an xml file from your application "ReportMaster" version 1.
Now in ReportMaster version 2 a some more attributes have been added that may or not be defined.
If you use the 'no tag means null' representation you get automatic backward compatibility for reading your ReportMaster 1 xml file.
You may like to try something like this which covers all the bases, including not relying on whitespace after the number:
>>> import re
>>> numeric_const_pattern = r"""
... [-+]? # optional sign
... (?:
... (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc
... |
... (?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc
... )
... # followed by optional exponent part if desired
... (?: [Ee] [+-]? \d+ ) ?
... """
>>> rx = re.compile(numeric_const_pattern, re.VERBOSE)
>>> rx.findall(".1 .12 9.1 98.1 1. 12. 1 12")
['.1', '.12', '9.1', '98.1', '1.', '12.', '1', '12']
>>> rx.findall("-1 +1 2e9 +2E+09 -2e-9")
['-1', '+1', '2e9', '+2E+09', '-2e-9']
>>> rx.findall("current level: -2.03e+99db")
['-2.03e+99']
>>>
For easy copy-pasting:
numeric_const_pattern = '[-+]? (?: (?: \d* \. \d+ ) | (?: \d+ \.? ) )(?: [Ee] [+-]? \d+ ) ?'
rx = re.compile(numeric_const_pattern, re.VERBOSE)
rx.findall("Some example: Jr. it. was .23 between 2.3 and 42.31 seconds")
If you know the root password, you can try
su -c "<command1> ; <command2>"
You can use https://github.com/mxcl/OMGHTTPURLRQ
id config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:someID];
id session = [NSURLSession sessionWithConfiguration:config delegate:someObject delegateQueue:[NSOperationQueue new]];
OMGMultipartFormData *multipartFormData = [OMGMultipartFormData new];
[multipartFormData addFile:data1 parameterName:@"file1" filename:@"myimage1.png" contentType:@"image/png"];
NSURLRequest *rq = [OMGHTTPURLRQ POST:url:multipartFormData];
id path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"upload.NSData"];
[rq.HTTPBody writeToFile:path atomically:YES];
[[session uploadTaskWithRequest:rq fromFile:[NSURL fileURLWithPath:path]] resume];
I just wanted to add that "Include" is part of eager loading. It is described in Entity Framework 6 tutorial by Microsoft. Here is the link: https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application
Excerpt from the linked page:
Here are several ways that the Entity Framework can load related data into the navigation properties of an entity:
Lazy loading. When the entity is first read, related data isn't retrieved. However, the first time you attempt to access a navigation property, the data required for that navigation property is automatically retrieved. This results in multiple queries sent to the database — one for the entity itself and one each time that related data for the entity must be retrieved. The DbContext class enables lazy loading by default.
Eager loading. When the entity is read, related data is retrieved along with it. This typically results in a single join query that retrieves all of the data that's needed. You specify eager loading by using the
Include
method.Explicit loading. This is similar to lazy loading, except that you explicitly retrieve the related data in code; it doesn't happen automatically when you access a navigation property. You load related data manually by getting the object state manager entry for an entity and calling the Collection.Load method for collections or the Reference.Load method for properties that hold a single entity. (In the following example, if you wanted to load the Administrator navigation property, you'd replace
Collection(x => x.Courses)
withReference(x => x.Administrator)
.) Typically you'd use explicit loading only when you've turned lazy loading off.Because they don't immediately retrieve the property values, lazy loading and explicit loading are also both known as deferred loading.
While I appreciate you believe absolute paths is not an option, it is a better option than relative paths and updating the PHP include path.
Use absolute paths with an constant you can set based on environment.
if (is_production()) {
define('ROOT_PATH', '/some/production/path');
}
else {
define('ROOT_PATH', '/root');
}
include ROOT_PATH . '/connect.php';
As commented, ROOT_PATH
could also be derived from the current path, $_SERVER['DOCUMENT_ROOT']
, etc.
When you do this:
export type Fruit = "Orange" | "Apple" | "Banana"
...you are creating a type called Fruit
that can only contain the literals "Orange"
, "Apple"
and "Banana"
. This type extends String
, hence it can be assigned to String
. However, String
does NOT extend "Orange" | "Apple" | "Banana"
, so it cannot be assigned to it. String
is less specific. It can be any string.
When you do this:
export type Fruit = "Orange" | "Apple" | "Banana"
const myString = "Banana";
const myFruit: Fruit = myString;
...it works. Why? Because the actual type of myString
in this example is "Banana"
. Yes, "Banana"
is the type. It is extends String
so it's assignable to String
. Additionally, a type extends a Union Type when it extends any of its components. In this case, "Banana"
, the type, extends "Orange" | "Apple" | "Banana"
because it extends one of its components. Hence, "Banana"
is assignable to "Orange" | "Apple" | "Banana"
or Fruit
.
My case was dodgy typing
myApp.factory('Notify',funtion(){
function has a 'c' !
Do
<script>//<![CDATA[
/* script */
//]]></script>
Try this. You can just use built-in ThresholdFilter
and LevelFilter
. No need to create your own filters programmically. In this example WARN and ERROR levels are logged to System.err and rest to System.out:
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<!-- deny ERROR level -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
</filter>
<!-- deny WARN level -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>DENY</onMatch>
</filter>
<target>System.out</target>
<immediateFlush>true</immediateFlush>
<encoder>
<charset>utf-8</charset>
<pattern>${msg_pattern}</pattern>
</encoder>
</appender>
<appender name="stderr" class="ch.qos.logback.core.ConsoleAppender">
<!-- deny all events with a level below WARN, that is INFO, DEBUG and TRACE -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
<target>System.err</target>
<immediateFlush>true</immediateFlush>
<encoder>
<charset>utf-8</charset>
<pattern>${msg_pattern}</pattern>
</encoder>
</appender>
<root level="WARN">
<appender-ref ref="stderr"/>
</root>
<root level="TRACE">
<appender-ref ref="stdout"/>
</root>
This worked for me:
:%s/^[^a-zA-Z0-9]$\n//ig
It basically deletes all the lines that don't have a number or letter. Since all the items in my list had letters, it deleted all the blank lines.
Just want to throw something in to help people still having this problem. (for me at least) the css is showing that it puts default classes of level1, level2, and level3 on each piece of the menu(level 1 being the menu, level2 being the first dropdown, level3 being the third popout). Setting the padding in css
.level2
{
padding: 2px 2px 2px 2px;
}
does work for adding the padding to each li in the first dropdown.
Read it and weep!
I figured it out. If you don't throw from the handler, the handler will just continue and so will the exception.
The magic happens when you throw you own exception and handle that.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <tchar.h>
void SignalHandler(int signal)
{
printf("Signal %d",signal);
throw "!Access Violation!";
}
int main()
{
typedef void (*SignalHandlerPointer)(int);
SignalHandlerPointer previousHandler;
previousHandler = signal(SIGSEGV , SignalHandler);
try{
*(int *) 0 = 0;// Baaaaaaad thing that should never be caught. You should write good code in the first place.
}
catch(char *e)
{
printf("Exception Caught: %s\n",e);
}
printf("Now we continue, unhindered, like the abomination never happened. (I am an EVIL genius)\n");
printf("But please kids, DONT TRY THIS AT HOME ;)\n");
}
urllib2.urlopen does an HTTP GET (or POST if you supply a data argument), not an HTTP HEAD (if it did the latter, you couldn't do readlines or other accesses to the page body, of course).
I use SFTP and its work for me.
I believe this will solve the issue
var z = '[{"name":"1","age":"2"},{"name":"1","age":"3"}]';
z = JSON.stringify(JSON.parse(z));
$.ajax({
url: "/setTest",
data: z,
type: "POST",
dataType:"json",
contentType:'application/json'
});
Typically you see this error after you have already done a redirect and then try to output some more data to the output stream. In the cases where I have seen this in the past, it is often one of the filters that is trying to redirect the page, and then still forwards through to the servlet. I cannot see anything immediately wrong with the servlet, so you might want to try having a look at any filters that you have in place as well.
Edit: Some more help in diagnosing the problem…
The first step to diagnosing this problem is to ascertain exactly where the exception is being thrown. We are assuming that it is being thrown by the line
getServletConfig().getServletContext()
.getRequestDispatcher("/GroupCopiedUpdt.jsp")
.forward(request, response);
But you might find that it is being thrown later in the code, where you are trying to output to the output stream after you have tried to do the forward. If it is coming from the above line, then it means that somewhere before this line you have either:
Good luck!
I actually found the right command to use.. its called timeout: http://www.ss64.com/nt/timeout.html
Using dataType: 'jsonp'
worked for me.
async function get_ajax_data(){
var _reprojected_lat_lng = await $.ajax({
type: 'GET',
dataType: 'jsonp',
data: {},
url: _reprojection_url,
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR)
},
success: function (data) {
console.log(data);
// note: data is already json type, you
// just specify dataType: jsonp
return data;
}
});
} // function
For those having trouble receiving the request on a php page using $_POST because you expect key-value pairs:
While all the answers where very helpful, I lacked some basic understanding on which string actually to post, since in the old apache HttpClient I used
new UrlEncodedFormEntity(nameValuePairs); (Java)
and then could use $_POST in php do get the key-value pairs.
To my understanding now one has build that string manually before posting. So the string needs to look like
val data = "key1=val1&key2=val2"
but instead just adding it to the url it is posted (in the header).
The alternative would be to use a json-string instead:
val data = "{\"key1\":\"val1\",\"key2\":\"val2\"}" // {"key1":"val1","key2":"val2"}
and pull it in php without $_POST:
$json_params = file_get_contents('php://input');
// echo_p("Data: $json_params");
$data = json_decode($json_params, true);
Here you find a sample code in Kotlin:
class TaskDownloadTest : AsyncTask<Void, Void, Void>() {
override fun doInBackground(vararg params: Void): Void? {
var urlConnection: HttpURLConnection? = null
try {
val postData = JsonObject()
postData.addProperty("key1", "val1")
postData.addProperty("key2", "val2")
// reformat json to key1=value1&key2=value2
// keeping json because I may change the php part to interpret json requests, could be a HashMap instead
val keys = postData.keySet()
var request = ""
keys.forEach { key ->
// Log.i("data", key)
request += "$key=${postData.get(key)}&"
}
request = request.replace("\"", "").removeSuffix("&")
val requestLength = request.toByteArray().size
// Warning in Android 9 you need to add a line in the application part of the manifest: android:usesCleartextTraffic="true"
// https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted
val url = URL("http://10.0.2.2/getdata.php")
urlConnection = url.openConnection() as HttpURLConnection
// urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") // apparently default
// Not sure what these are for, I do not use them
// urlConnection.setRequestProperty("Content-Type", "application/json")
// urlConnection.setRequestProperty("Key","Value")
urlConnection.readTimeout = 5000
urlConnection.connectTimeout = 5000
urlConnection.requestMethod = "POST"
urlConnection.doOutput = true
// urlConnection.doInput = true
urlConnection.useCaches = false
urlConnection.setFixedLengthStreamingMode(requestLength)
// urlConnection.setChunkedStreamingMode(0) // if you do not want to handle request length which is fine for small requests
val out = urlConnection.outputStream
val writer = BufferedWriter(
OutputStreamWriter(
out, "UTF-8"
)
)
writer.write(request)
// writer.write("{\"key1\":\"val1\",\"key2\":\"val2\"}") // {"key1":"val1","key2":"val2"} JsonFormat or just postData.toString() for $json_params=file_get_contents('php://input'); json_decode($json_params, true); in php
// writer.write("key1=val1&key2=val2") // key=value format for $_POST in php
writer.flush()
writer.close()
out.close()
val code = urlConnection.responseCode
if (code != 200) {
throw IOException("Invalid response from server: $code")
}
val rd = BufferedReader(
InputStreamReader(
urlConnection.inputStream
)
)
var line = rd.readLine()
while (line != null) {
Log.i("data", line)
line = rd.readLine()
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
urlConnection?.disconnect()
}
return null
}
}
You can try this:
var driveName = "C:\\";
var freeSpace = DriveInfo.GetDrives().Where(x => x.Name == driveName && x.IsReady).FirstOrDefault().TotalFreeSpace;
Good luck
I think op wants to know what the font that is used on a webpage is, and hoped that info might be findable in the 'inspect' pane.
Try adding the Whatfont Chrome extension.
Use format string
intNum = 123
print "0x%x"%(intNum)
or hex
function.
intNum = 123
print hex(intNum)
Here is what works for me on Swift 3
let _ = (dict[key].map { $0 as? String } ?? "")
I was getting the below error when i was trying to launch a new conatier- listen tcp 0.0.0.0:8080: bind: address already in use.
Solution: netstat -tulnp | grep 8080
[[email protected] (aws_main) ~]# netstat -tulnp | grep 8080 tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 12749/java [[email protected] (aws_main) ~]#
kill -9 12749
Then try to relaunch the container it should work
try this, tested on windows platform and it works fine :
from selenium import webdriver
browser = webdriver.Chrome('C:\\Users\\yeivic\\Downloads\\chromedriver')
browser.fullscreen_window()
browser.get('http://google.com/')
Just took a look over the mustache docs and they support "inverted sections" in which they state
they (inverted sections) will be rendered if the key doesn't exist, is false, or is an empty list
http://mustache.github.io/mustache.5.html#Inverted-Sections
{{#value}}
value is true
{{/value}}
{{^value}}
value is false
{{/value}}
With Eloquent its very easy to retrieve relational data. Checkout the following example with your scenario in Laravel 5.
We have three models:
1) Article (belongs to user and category)
2) Category (has many articles)
3) User (has many articles)
1) Article.php
<?php
namespace App\Models;
use Eloquent;
class Article extends Eloquent{
protected $table = 'articles';
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function category()
{
return $this->belongsTo('App\Models\Category');
}
}
2) Category.php
<?php
namespace App\Models;
use Eloquent;
class Category extends Eloquent
{
protected $table = "categories";
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
3) User.php
<?php
namespace App\Models;
use Eloquent;
class User extends Eloquent
{
protected $table = 'users';
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
You need to understand your database relation and setup in models. User has many articles. Category has many articles. Articles belong to user and category. Once you setup the relationships in Laravel, it becomes easy to retrieve the related information.
For example, if you want to retrieve an article by using the user and category, you would need to write:
$article = \App\Models\Article::with(['user','category'])->first();
and you can use this like so:
//retrieve user name
$article->user->user_name
//retrieve category name
$article->category->category_name
In another case, you might need to retrieve all the articles within a category, or retrieve all of a specific user`s articles. You can write it like this:
$categories = \App\Models\Category::with('articles')->get();
$users = \App\Models\Category::with('users')->get();
You can learn more at http://laravel.com/docs/5.0/eloquent
in 5.7 version. 'password' field has been deleted. 'authentication_string' replace it
use mysql;
update user set authentication_string=password('123456') where user='root';
flush privileges;
Have you tried to remove the proxy username and password? A similar poster encountered that issue:
Failing that I found the following worked:
mvn dependency:resolve
Tip: update_attribute
is being deprecated in Rails 4 via Commit a7f4b0a1. It removes update_attribute
in favor of update_column
.
With a readily available Node module, it is possible to get full-length stack traces out of Node (albeit with a minor performance penalty): http://www.mattinsler.com/post/26396305882/announcing-longjohn-long-stack-traces-for-node-js
div.classList.add("foo");
div.classList.remove("foo");
More at https://developer.mozilla.org/en-US/docs/Web/API/element.classList
in JetPack it work for me
NavigationUI.setupWithNavController(vb.toolbar, nav)
vb.toolbar.navigationIcon = ResourcesCompat.getDrawable(resources, R.drawable.icon_home, null)
The default value for client_max_body_size
directive is 1 MiB.
It can be set in http
, server
and location
context — as in the most cases,
this directive in a nested block takes precedence over the same directive in the ancestors blocks.
Excerpt from the ngx_http_core_module documentation:
Syntax: client_max_body_size size; Default: client_max_body_size 1m; Context: http, server, location
Sets the maximum allowed size of the client request body, specified in the “Content-Length” request header field. If the size in a request exceeds the configured value, the 413 (Request Entity Too Large) error is returned to the client. Please be aware that browsers cannot correctly display this error. Setting size to 0 disables checking of client request body size.
Don't forget to reload configuration
by nginx -s reload
or service nginx reload
commands prepending with sudo
(if any).
Two options for runtime type checking with generics:
Option 1 - Corrupt your constructor
Let's assume you are overriding indexOf(...), and you want to check the type just for performance, to save yourself iterating the entire collection.
Make a filthy constructor like this:
public MyCollection<T>(Class<T> t) {
this.t = t;
}
Then you can use isAssignableFrom to check the type.
public int indexOf(Object o) {
if (
o != null &&
!t.isAssignableFrom(o.getClass())
) return -1;
//...
Each time you instantiate your object you would have to repeat yourself:
new MyCollection<Apples>(Apples.class);
You might decide it isn't worth it. In the implementation of ArrayList.indexOf(...), they do not check that the type matches.
Option 2 - Let it fail
If you need to use an abstract method that requires your unknown type, then all you really want is for the compiler to stop crying about instanceof. If you have a method like this:
protected abstract void abstractMethod(T element);
You can use it like this:
public int indexOf(Object o) {
try {
abstractMethod((T) o);
} catch (ClassCastException e) {
//...
You are casting the object to T (your generic type), just to fool the compiler. Your cast does nothing at runtime, but you will still get a ClassCastException when you try to pass the wrong type of object into your abstract method.
NOTE 1: If you are doing additional unchecked casts in your abstract method, your ClassCastExceptions will get caught here. That could be good or bad, so think it through.
NOTE 2: You get a free null check when you use instanceof. Since you can't use it, you may need to check for null with your bare hands.
This webpage have an explanation and a solution.
The solution is:
To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:
vm.overcommit_memory = 2
vm.overcommit_ratio = 80
// To open a new tab in an existing window
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
There is no builtin feature to wait for any process to finish.
You could send kill -0
to any PID found, so you don't get puzzled by zombies and stuff that will still be visible in ps
(while still retrieving the PID list using ps
).
you can do something like that:
where regexp_like(name, 'string$', 'i');
Sharer.php no longer allows you to customize. The page you share will be scraped for OG Tags and that data will be shared.
To properly customize, use FB.UI
which comes with the JS-SDK.
In a word no.
In two, not yet.
There is, however, an open issue for a --no-build
flag to npm install
to perform an installation without building, which could be used to do what you're asking.
See this open issue.
A minor improvement on d4nt's answer, as you probably want to check for errors and not have to change xcopy paths if you're working on a server and development machine:
public void CopyFolder(string source, string destination)
{
string xcopyPath = Environment.GetEnvironmentVariable("WINDIR") + @"\System32\xcopy.exe";
ProcessStartInfo info = new ProcessStartInfo(xcopyPath);
info.UseShellExecute = false;
info.RedirectStandardOutput = true;
info.Arguments = string.Format("\"{0}\" \"{1}\" /E /I", source, destination);
Process process = Process.Start(info);
process.WaitForExit();
string result = process.StandardOutput.ReadToEnd();
if (process.ExitCode != 0)
{
// Or your own custom exception, or just return false if you prefer.
throw new InvalidOperationException(string.Format("Failed to copy {0} to {1}: {2}", source, destination, result));
}
}
Here is a java 8 method to find a string in a text file:
for (String toFindUrl : urlsToTest) {
streamService(toFindUrl);
}
private void streamService(String item) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(lines -> lines.contains(item))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named __init__.py
in the same directory.
Answering my own question for documentation. I'm sure there are other ways to accomplish this, but this works and this code is tested.
<html>
<head>
<script language="Javascript" src="javascript/jquery-1.2.6.min.js"></script>
<script type="text/JavaScript">
$(function() {
$(".update").bind("click", // bind the click event to a div
function() {
var selectOption = $('.selDiv').children('.opts') ;
var _this = $(this).next().children(".opts") ;
$(selectOption).find("option[index='0']").attr("selected","selected");
// $(selectOption).find("option[value='DEFAULT']").attr("selected","selected");
// $(selectOption).find("option[text='Default']").attr("selected","selected");
// $(_this).find("option[value='DEFAULT']").attr("selected","selected");
// $(_this).find("option[text='Default']").attr("selected","selected");
// $(_this).find("option[index='0']").attr("selected","selected");
}); // END Bind
}); // End eventlistener
</script>
</head>
<body>
<div class="update" style="height:50px; color:blue; cursor:pointer;">Update</div>
<div class="selDiv">
<select class="opts">
<option selected value="DEFAULT">Default</option>
<option value="SEL1">Selection 1</option>
<option value="SEL2">Selection 2</option>
</select>
</div>
</body>
</html>
The simple solution is to comment it out.
$a="test";
if("test"==$a)
{
//echo "yes"; //no longer needed - 7/7/2014 - updateded bla bla to do foo
}
The added benefit is your not changing your original code and you can date it, initial it and put a reason why.
Why the down vote, according to the OP request I think this is a perfectly valid solution.
"I want to [break the if statement above and] stop executing echo "yes"; or such codes which are no longer necessary to be executed, there may be or may not be an additional condition, is there way to do this?"
In fact someone could look at some of the other solutions, a year latter and wonder what is going on there. As per my suggestion, one could leave good documentation for future reference, which is always good practice.
Yes this is possible
Since the question is update, this solution can only gives you the embed url not the HLS url, check @JAL answer.
with the ressource search.list
and the parameters:
* part: id
* channelId: UCURGpU4lj3dat246rysrWsw
* eventType: live
* type: video
Request :
GET https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCURGpU4lj3dat246rysrWsw&eventType=live&type=video&key={YOUR_API_KEY}
Result:
"items": [
{
"kind": "youtube#searchResult",
"etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/enc3-yCp8APGcoiU_KH-mSKr4Yo\"",
"id": {
"kind": "youtube#video",
"videoId": "WVZpCdHq3Qg"
}
},
Then get the videoID
value WVZpCdHq3Qg for example and add the value to this url:
https://www.youtube.com/embed/ + videoID
https://www.youtube.com/watch?v= + videoID
Just use a RETURN (it will work both inside and outside a stored procedure).
Move DropDownList1.Items.Add(new ListItem("Select", "0", true)); After bindStatusDropDownList();
so:
if (!IsPostBack)
{
bindStatusDropDownList(); //first create structure
DropDownList1.Items.Add(new ListItem("Select", "0", true)); // after add item
}
First, it usually does not matter that much in practice. Most hash functions are "good enough".
But if you really care, you should know that it is a research subject by itself. There are thousand of papers about that. You can still get a PhD today by studying & designing hashing algorithms.
Your second hash function might be slightly better, because it probably should separate the string "ab"
from the string "ba"
. On the other hand, it is probably less quick than the first hash function. It may, or may not, be relevant for your application.
I'll guess that hash functions used for genome strings are quite different than those used to hash family names in telephone databases. Perhaps even some string hash functions are better suited for German, than for English or French words.
Many software libraries give you good enough hash functions, e.g. Qt has qhash, and C++11 has std::hash in <functional>
, Glib has several hash functions in C, and POCO has some hash function.
I quite often have hashing functions involving primes (see Bézout's identity) and xor, like e.g.
#define A 54059 /* a prime */
#define B 76963 /* another prime */
#define C 86969 /* yet another prime */
#define FIRSTH 37 /* also prime */
unsigned hash_str(const char* s)
{
unsigned h = FIRSTH;
while (*s) {
h = (h * A) ^ (s[0] * B);
s++;
}
return h; // or return h % C;
}
But I don't claim to be an hash expert. Of course, the values of A
, B
, C
, FIRSTH
should preferably be primes, but you could have chosen other prime numbers.
Look at some MD5 implementation to get a feeling of what hash functions can be.
Most good books on algorithmics have at least a whole chapter dedicated to hashing. Start with wikipages on hash function & hash table.
Although the question was for SQL Server 2008 R2, in case someone is reading this with version 2012 and above, since then it became much easier by the use of FORMAT.
You can either pass a standard numeric format string or a custom numeric format string as the format argument (thank Vadim Ovchinnikov for this hint).
For this question for example a code like
DECLARE @myInt INT = 1;
-- One way using a standard numeric format string
PRINT FORMAT(@myInt,'D3');
-- Other way using a custom numeric format string
PRINT FORMAT(@myInt,'00#');
outputs
001
001
This maven dependency will solve your problem:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.6.5</version>
</dependency>
One thing I've struggled is that for ZonedDateTime timezone being changed to GMT during deserialization. Turned out, that by default jackson replaces it with one from context.. To keep zone one must disable this 'feature'
Jackson2ObjectMapperBuilder.json()
.featuresToDisable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
List<object>.AddRange(object[])
should do the trick. It will avoid all sorts of useless memory allocation.
You could also use Linq, somewhat like this: object[].Cast<object>().ToList()
What I want to say here is like some kind of add-on on @Suciu Lucian's answer.
The weird situation I ran into is that when I apply the solution of @Suciu Lucian in my file, it works in Chrome but not in Safari (and did not try in Firefox). After I studied the guide of styling table border published by w3.org, I found something alternative:
table.myTable{
border-spacing: 0;
}
table.myTable td{
border-bottom:1px solid red;
}
Yes you have to style the td
instead of the tr
.
consider adding a new method to BusinessClass:
public static function fromStdClass(\stdClass $in): BusinessClass
{
$out = new self();
$reflection_object = new \ReflectionObject($in);
$reflection_properties = $reflection_object->getProperties();
foreach ($reflection_properties as $reflection_property)
{
$name = $reflection_property->getName();
if (property_exists('BusinessClass', $name))
{
$out->{$name} = $in->$name;
}
}
return $out;
}
then you can make a new BusinessClass from $stdClass:
$converted = BusinessClass::fromStdClass($stdClass);
Text printed to stderr will show up in httpd's error log when running under mod_wsgi. You can either use print
directly, or use logging
instead.
print >>sys.stderr, 'Goodbye, cruel world!'
When I needed to create similar dots in input[password] I use a custom font in base64 (with 2 glyphs see above 25CF and 2022)
SCSS styles
@font-face {
font-family: 'pass';
font-style: normal;
font-weight: 400;
src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATsAA8AAAAAB2QAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABWAAAABwAAAAcg9+z70dERUYAAAF0AAAAHAAAAB4AJwANT1MvMgAAAZAAAAA/AAAAYH7AkBhjbWFwAAAB0AAAAFkAAAFqZowMx2N2dCAAAAIsAAAABAAAAAQAIgKIZ2FzcAAAAjAAAAAIAAAACAAAABBnbHlmAAACOAAAALkAAAE0MwNYJ2hlYWQAAAL0AAAAMAAAADYPA2KgaGhlYQAAAyQAAAAeAAAAJAU+ATJobXR4AAADRAAAABwAAAAcCPoA6mxvY2EAAANgAAAAEAAAABAA5gFMbWF4cAAAA3AAAAAaAAAAIAAKAE9uYW1lAAADjAAAARYAAAIgB4hZ03Bvc3QAAASkAAAAPgAAAE5Ojr8ld2ViZgAABOQAAAAGAAAABuK7WtIAAAABAAAAANXulPUAAAAA1viLwQAAAADW+JM4eNpjYGRgYOABYjEgZmJgBEI2IGYB8xgAA+AANXjaY2BifMg4gYGVgYVBAwOeYEAFjMgcp8yiFAYHBl7VP8wx/94wpDDHMIoo2DP8B8kx2TLHACkFBkYA8/IL3QB42mNgYGBmgGAZBkYGEEgB8hjBfBYGDyDNx8DBwMTABmTxMigoKKmeV/3z/z9YJTKf8f/X/4/vP7pldosLag4SYATqhgkyMgEJJnQFECcMOGChndEAfOwRuAAAAAAiAogAAQAB//8AD3jaY2BiUGJgYDRiWsXAzMDOoLeRkUHfZhM7C8Nbo41srHdsNjEzAZkMG5lBwqwg4U3sbIx/bDYxgsSNBRUF1Y0FlZUYBd6dOcO06m+YElMa0DiGJIZUxjuM9xjkGRhU2djZlJXU1UDQ1MTcDASNjcTFQFBUBGjYEkkVMJCU4gcCKRTeHCk+fn4+KSllsJiUJEhMUgrMUQbZk8bgz/iA8SRR9qzAY087FjEYD2QPDDAzMFgyAwC39TCRAAAAeNpjYGRgYADid/fqneL5bb4yyLMwgMC1H90HIfRkCxDN+IBpFZDiYGAC8QBbSwuceNpjYGRgYI7594aBgcmOAQgYHzAwMqACdgBbWQN0AAABdgAiAAAAAAAAAAABFAAAAj4AYgI+AGYB9AAAAAAAKgAqACoAKgBeAJIAmnjaY2BkYGBgZ1BgYGIAAUYGBNADEQAFQQBaAAB42o2PwUrDQBCGvzVV9GAQDx485exBY1CU3PQgVgIFI9prlVqDwcZNC/oSPoKP4HNUfQLfxYN/NytCe5GwO9/88+/MBAh5I8C0VoAtnYYNa8oaXpAn9RxIP/XcIqLreZENnjwvyfPieVVdXj2H7DHxPJH/2/M7sVn3/MGyOfb8SWjOGv4K2DRdctpkmtqhos+D6ISh4kiUUXDj1Fr3Bc/Oc0vPqec6A8aUyu1cdTaPZvyXyqz6Fm5axC7bxHOv/r/dnbSRXCk7+mpVrOqVtFqdp3NKxaHUgeod9cm40rtrzfrt2OyQa8fppCO9tk7d1x0rpiQcuDuRkjjtkHt16ctbuf/radZY52/PnEcphXpZOcofiEZNcQAAeNpjYGIAg///GBgZsAF2BgZGJkZmBmaGdkYWRla29JzKggxD9tK8TAMDAxc2D0MLU2NjENfI1M0ZACUXCrsAAAABWtLiugAA) format('woff');
}
input.password {
font-family: 'pass', 'Roboto', Helvetica, Arial, sans-serif ;
font-size: 18px;
&::-webkit-input-placeholder {
transform: scale(0.77);
transform-origin: 0 50%;
}
&::-moz-placeholder {
font-size: 14px;
opacity: 1;
}
&:-ms-input-placeholder {
font-size: 14px;
font-family: 'Roboto', Helvetica, Arial, sans-serif;
}
After that, I got identical display input[password]
I had a similar problem of getting a black screen appear on sliding transition from one activity to another using overridependingtransition
. and I followed the way below and it worked
1) created a noanim.xml
in anim folder
<?xml version="1.0" encoding="utf-8"?>
<translate
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="@android:integer/config_longAnimTime"
android:fromYDelta="0%p"
android:toYDelta="0%p" />
and used
overridePendingTransition(R.drawable.lefttorightanim, R.anim.noanim);
The first parameter as my original animation and second parameter which is the exit animation as my dummy animation
Remember that Constructor of an object is called immediately after the memory is allocated for that object and whereas the destructor is called just before deallocating the memory of that object.
Since you've already looked into strtok
just continue down the same path and split your string using space (' '
) as a delimiter, then use something as realloc
to increase the size of the array containing the elements to be passed to execvp
.
See the below example, but keep in mind that strtok
will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy
or similar function.
char str[]= "ls -l";
char ** res = NULL;
char * p = strtok (str, " ");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p;
p = strtok (NULL, " ");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
res[0] = ls
res[1] = -l
res[2] = (null)
In my case setting width to all divs helped:
.page-content div {
width: auto !important;
max-width: 99%;
}
There are two ways to know the about Sybase version,
1) Using this System procedure to get the information about Sybase version
> sp_version
> go
2) Using this command to get Sybase version
> select @@version
> go
This should be like
str_replace("\n", '', $str); str_replace("\r", '', $str); str_replace("\r\n", '', $str);
I faced to the same problem. I solved it by
HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath
and edit the default key with the output of
C:\> where python.exe
command.HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath\InstallGroup
and edit the default key with Python 3.4
Note: My python version is 3.4 and you need to replace 3.4 with your python version.
Normally you can find Registry entries for Python in HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\<version>
. You just need to copy those entries to HKEY_CURRENT_USER\Software\Python\PythonCore\<version>
os.path.abspath('D:\Dir1\Dir2\..')
>>> 'D:\Dir1'
So a ..
helps
To align a text use the following:
StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;
e.Graphics.DrawString("My String", this.Font, Brushes.Black, ClientRectangle, sf);
Please note that the text here is aligned in the given bounds. In this sample this is the ClientRectangle.
To make sure a click only actions once use this:
$(".bet").unbind().click(function() {
//Stuff
});
Set a height to the last placeholder div.
<div class="row" style="height:30px;">
<!--placeholder to make the whole block has valid auto height-->
Do you mean like this
int index = 2;
string s = "hello";
Console.WriteLine(s[index]);
string also implements IEnumberable<char>
so you can also enumerate it like this
foreach (char c in s)
Console.WriteLine(c);
Simply move the declaration outside of the if block.
@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="";
if (currentstore == "www.mydomain.com")
{
<link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store1_logo.jpg";
}
else
{
<link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store2_logo.gif";
}
}
<a href="@Url.RouteUrl("HomePage")" class="logo"><img alt="" src="@imgsrc"></a>
You could make it a bit cleaner.
@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="/content/images/uploaded/store2_logo.gif";
if (currentstore == "www.mydomain.com")
{
<link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store1_logo.jpg";
}
else
{
<link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
}
}
You can use the VBA string functions (as @onedaywhen points out in the comments, they are not really the VBA functions, but their equivalents from the MS Jet libraries. As far as function signatures go, they are called and work the same, even though the actual presence of MS Access is not required for them to be available.):
SELECT DISTINCT Left(LastName, 1)
FROM Authors;
SELECT DISTINCT Mid(LastName, 1, 1)
FROM Authors;
You need to to use FileAPI. It is available in the latest FF & Chrome, but not IE9. Grab any md5 JS implementation suggested above. I've tried this and abandoned it because JS was too slow (minutes on large image files). Might revisit it if someone rewrites MD5 using typed arrays.
Code would look something like this:
HTML:
<input type="file" id="file-dialog" multiple="true" accept="image/*">
JS (w JQuery)
$("#file-dialog").change(function() {
handleFiles(this.files);
});
function handleFiles(files) {
for (var i=0; i<files.length; i++) {
var reader = new FileReader();
reader.onload = function() {
var md5 = binl_md5(reader.result, reader.result.length);
console.log("MD5 is " + md5);
};
reader.onerror = function() {
console.error("Could not read the file");
};
reader.readAsBinaryString(files.item(i));
}
}
I believe that, if you need to use the %20
variant, you could perhaps use rawurlencode()
.
Even if you are using IIS or apache, in my guess you are using static html page as a landing page, and by default the web server doesn't allow POST or GET verb on .html page, facebook calls your page via POST/GET verb
the solution would be to rename the page into .php or .aspx and you should be good to go :)
This answer is, as I write this, nearly eight years old, and about five years stale. But it's still (as I write this) the "accepted" answer, because it answered the question when it was asked.
The newer answer, that applies to the newer Android Studio tools, can be found here: https://stackoverflow.com/a/35828035/62 -- it's a great answer with screen shots. If you're using Android Studio, ignore the Eclipse answer below.
I was searching for the answer to this question, and was unsatisfied with the above answers. But then I found the answer, so here it is for future reference:
To summarize (and clarify), in Eclipse, go to "Debug Configurations". You can find that in the drop-down under the "debug" icon. Select "target", and select a preferred emulator target to launch. Then under "additional emulator command line options," add this:
-partition-size 1024
Then CLOSE the emulator (and remove any devices), and click the debug icon, which will launch the preferred emulator you selected. This is important: Eclipse needs to launch the debugger, not AVD.
That fixed the problem for me.
Please see below typescript for re-applying css class again to an element to override parent container (usually a framework component) css styles and force your custom styles. Your app framework (be it angular/react, probably does this so the parent container css was re-applied and none of your expected effects in css-class-name is showing up for your child element. Call this.overrideParentCssRule(childElement, 'css-class-name'); to do what the framework just did (call this in document.ready or end of event handler):
overrideParentCssRule(elem: HTMLElement, className: string) {
let cssRules = this.getCSSStyle(className);
for (let r: number = 0; r < cssRules.length; r++) {
let rule: CSSStyleRule = cssRules[r];
Object.keys(rule.style).forEach(s => {
if (isNaN(Number(s)) && rule.style[s]) {
elem.style[s] = rule.style[s];
}
});
}
}
Seems that only index.js get loaded when you require("./routes") . I used the following code in index.js to load the rest of the routes:
var fs = require('fs')
, path = require('path');
fs.readdirSync(__dirname).forEach(function(file){
var route_fname = __dirname + '/' + file;
var route_name = path.basename(route_fname, '.js');
if(route_name !== 'index' && route_name[0] !== "."){
exports[route_name] = require(route_fname)[route_name];
}
});
I'm going to post this answer under the following assumptions.
1) You (un)selected the checkbox on the first page and submitted the form.
2) Your building the second form and you setting the value="" true/false depending on if the previous one was checked.
3) You want the checkbox to reflect if it was checked or not before.
If this is the case then you can do something like:
var $checkbox1 = $('#checkbox1');
$checkbox1.prop('checked', $checkbox1.val() === 'true');
As mentioned by alko989, there is a major security flaw with _blank
(details here).
To avoid it from pure JS code:
const openInNewTab = (url) => {
const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
if (newWindow) newWindow.opener = null
}
Then add to your onClick
onClick={() => openInNewTab('https://stackoverflow.com')}
The third param can also take these optional values, based on your needs.
Adding to @Vityata 's answer, below is the function I use to convert a row / column vector in a 1D array:
Function convertVecToArr(ByVal rng As Range) As Variant
'convert two dimension array into a one dimension array
Dim arr() As Variant, slicedArr() As Variant
arr = rng.value 'arr = rng works too (https://bettersolutions.com/excel/cells-ranges/vba-working-with-arrays.htm)
If UBound(arr, 1) > UBound(arr, 2) Then
slicedArr = Application.WorksheetFunction.Transpose(arr)
Else
slicedArr = Application.WorksheetFunction.index(arr, 1, 0) 'If you set row_num or column_num to 0 (zero), Index returns the array of values for the entire column or row, respectively._
'To use values returned as an array, enter the Index function as an array formula in a horizontal range of cells for a row,_
'and in a vertical range of cells for a column.
'https://usefulgyaan.wordpress.com/2013/06/12/vba-trick-of-the-week-slicing-an-array-without-loop-application-index/
End If
convertVecToArr = slicedArr
End Function
I have this little toy, that also deals with non generic interfaces. I'm OK with it throwing a ClassCastException if feed wrong (OK and happy)
public class TypeUtil {
public static long castToLong(Object o) {
Number n = (Number) o;
return n.longValue();
}
}
Alternative
If your console is not empty, right click on the Console area > Preferences... > change the value for the Console buffer size (characters) (recommended) or uncheck the Limit console output (not recommended):
Right click on pom.xml, Run As, you should see the list of m2 options if you have Maven installed, you can select Maven Clean from there
As has already been said: figure
will create a new figure for your next plots. While calling figure
you can also configure it. Example:
figHandle = figure('Name', 'Name of Figure', 'OuterPosition',[1, 1, scrsz(3), scrsz(4)]);
The example sets the name for the window and the outer size of it in relation to the used screen.
Here figHandle
is the handle to the resulting figure and can be used later to change appearance and content. Examples:
Dot notation:
figHandle.PaperOrientation = 'portrait';
figHandle.PaperUnits = 'centimeters';
Old Style:
set(figHandle, 'PaperOrientation', 'portrait', 'PaperUnits', 'centimeters');
Using the handle with dot notation or set
, options for printing are configured here.
By keeping the handles for the figures with distinc names you can interact with multiple active figures. To set a existing figure as your active, call figure(figHandle)
. New plots will go there now.
I try GET 'http://example.com/?var=value'
Important use '
add >/dev/null 2>&1
for not send email when this activate
Sorry for my English
On mac, press Command + R
or got to Database
-> Reverse Engineer
and keep selecting your requirements and continue
You cannot append to an existing xlsx file with xlsxwriter
.
There is a module called openpyxl which allows you to read and write to preexisting excel file, but I am sure that the method to do so involves reading from the excel file, storing all the information somehow (database or arrays), and then rewriting when you call workbook.close()
which will then write all of the information to your xlsx file.
Similarly, you can use a method of your own to "append" to xlsx documents. I recently had to append to a xlsx file because I had a lot of different tests in which I had GPS data coming in to a main worksheet, and then I had to append a new sheet each time a test started as well. The only way I could get around this without openpyxl was to read the excel file with xlrd and then run through the rows and columns...
i.e.
cells = []
for row in range(sheet.nrows):
cells.append([])
for col in range(sheet.ncols):
cells[row].append(workbook.cell(row, col).value)
You don't need arrays, though. For example, this works perfectly fine:
import xlrd
import xlsxwriter
from os.path import expanduser
home = expanduser("~")
# this writes test data to an excel file
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
sheet1 = wb.add_worksheet()
for row in range(10):
for col in range(20):
sheet1.write(row, col, "test ({}, {})".format(row, col))
wb.close()
# open the file for reading
wbRD = xlrd.open_workbook("{}/Desktop/test.xlsx".format(home))
sheets = wbRD.sheets()
# open the same file for writing (just don't write yet)
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
# run through the sheets and store sheets in workbook
# this still doesn't write to the file yet
for sheet in sheets: # write data from old file
newSheet = wb.add_worksheet(sheet.name)
for row in range(sheet.nrows):
for col in range(sheet.ncols):
newSheet.write(row, col, sheet.cell(row, col).value)
for row in range(10, 20): # write NEW data
for col in range(20):
newSheet.write(row, col, "test ({}, {})".format(row, col))
wb.close() # THIS writes
However, I found that it was easier to read the data and store into a 2-dimensional array because I was manipulating the data and was receiving input over and over again and did not want to write to the excel file until it the test was over (which you could just as easily do with xlsxwriter since that is probably what they do anyway until you call .close()
).
1) To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
2) To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
3) To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
4) To remove white space at both ends:
df.columns = df.columns.str.strip()
5) To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7) To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
I solved it this way: download the zipped package from here and follow this set of instructions:
unzip /path/to/downloads/folder/mysql-connector-python-VER.zip
In case u got a .gz
u can use ->
tar xzf mysql-connector-python-VER.tar.gz
And then:
cd mysql-connector-python-VER # move into the directory
sudo python3 setup.py install # NOTICE I USED PYTHON3 INSTEAD OF PYTHON
You can read about it here
Here is an example how I do it.
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import java.util.Map;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>() {
}.getType();
MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
formData.add("key1", "value1");
formData.add("key1", "value2");
WebTarget webTarget = ClientBuilder.newClient().target("https://some.server.url/");
String response = webTarget.path("subpath/subpath2").request().post(Entity.form(formData), String.class);
Map<String, String> gsonResponse = gson.fromJson(response, type);
There is a much simpler way. Put your picture in a comment box within the description cell. That way you only have one column and when you sort the picture will always stay with the description. Okay... Right click the cell containing the description... Insert comment...right click the outer border... Format comment...colours and lines tab... Colour drop down...Fill effects...Picture tab...select picture...browse for your picture (it might be best to keep all pictures in one folder for ease of placement)...ok... you will probably need to go to the size tab and frig around with the height and width. Done... You now only need to mouse over the red in the top right corner of the cell and the picture will appear...like magic.
This method means that the row height can be kept to a minimum and the pictures can be as big as you like.
If you want to validate individual form field, but don't want for UI to be triggered and display any validation errors, you may consider to use Validator.check() method which returns if given field passes validation or not.
Here is example
var validator = $("#form").data('validator');
if(validator.check('#element')){
/*field is valid*/
}else{
/*field is not valid (but no errors will be displayed)*/
}
It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.
In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue"
to then end of the URL you are opening. :
http://www.somesite.com/send.php?variableName=someValue
or
http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue
This way, from PHP you can access this value as:
$phpVariableName = $_POST["variableName"];
for forms using POST method or:
$phpVariableName = $_GET["variableName"];
for forms using GET method or the append to url method I've mentioned above (querystring).
A TreeMap is probably the most straightforward way of doing this. You use it exactly like a normal Map. i.e.
Map<Float,String> mySortedMap = new TreeMap<Float,MyObject>();
// Put some values in it
mySortedMap.put(1.0f,"One");
mySortedMap.put(0.0f,"Zero");
mySortedMap.put(3.0f,"Three");
// Iterate through it and it'll be in order!
for(Map.Entry<Float,String> entry : mySortedMap.entrySet()) {
System.out.println(entry.getValue());
} // outputs Zero One Three
It's worth taking a look at the API docs, http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html to see what else you can do with it.
You could also use float and inline-block to center your nav like the following:
nav li {
float: left;
}
nav {
display: inline-block;
}
I compared the suggested alternatives for speed and found that, for large enough vectors/matrices to fill, all alternatives except val * ones
and array(n * [val])
are equally fast.
Code to reproduce the plot:
import numpy
import perfplot
val = 42.0
def fill(n):
a = numpy.empty(n)
a.fill(val)
return a
def colon(n):
a = numpy.empty(n)
a[:] = val
return a
def full(n):
return numpy.full(n, val)
def ones_times(n):
return val * numpy.ones(n)
def list(n):
return numpy.array(n * [val])
perfplot.show(
setup=lambda n: n,
kernels=[fill, colon, full, ones_times, list],
n_range=[2 ** k for k in range(20)],
logx=True,
logy=True,
xlabel="len(a)",
)
Just the same way as you would do in normal Java code.
for (Map.Entry<String, String> entry : countries.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// ...
}
However, scriptlets (raw Java code in JSP files, those <% %>
things) are considered a poor practice. I recommend to install JSTL (just drop the JAR file in /WEB-INF/lib
and declare the needed taglibs in top of JSP). It has a <c:forEach>
tag which can iterate over among others Map
s. Every iteration will give you a Map.Entry
back which in turn has getKey()
and getValue()
methods.
Here's a basic example:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="${map}" var="entry">
Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>
Thus your particular issue can be solved as follows:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<select name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
You need a Servlet
or a ServletContextListener
to place the ${countries}
in the desired scope. If this list is supposed to be request-based, then use the Servlet
's doGet()
:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> countries = MainUtils.getCountries();
request.setAttribute("countries", countries);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
Or if this list is supposed to be an application-wide constant, then use ServletContextListener
's contextInitialized()
so that it will be loaded only once and kept in memory:
public void contextInitialized(ServletContextEvent event) {
Map<String, String> countries = MainUtils.getCountries();
event.getServletContext().setAttribute("countries", countries);
}
In both cases the countries
will be available in EL by ${countries}
.
Hope this helps.
You can easily append to the end of a file, by using the redirection char twice (>>
).
This will copy source.txt
to destination.txt
, overwriting destination in the process:
type source.txt > destination.txt
This will copy source.txt
to destination.txt
, appending to destination in the process:
type source.txt >> destination.txt
I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even
SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;
RichTextBox will allow you to use html to specify the color. Another alternative is using a listbox and using the DrawItem event to draw how you would like. AFAIK, textbox itself can't be used in the way you're hoping.
You need too loop through the array, remembering the smallest value you've seen so far. Like this:
int smallest = INT_MAX;
for (int i = 0; i < array_length; i++) {
if (array[i] < smallest) {
smallest = array[i];
}
}
$('IFRAME#currentElement').get(0).contentDocument.location.reload()
to order after the colsum :
order(colSums(people),decreasing=TRUE)
if more than 20+ columns
order(colSums(people[,c(5:25)],decreasing=TRUE) ##in case of keeping the first 4 columns remaining.
This question may be old, but for anybody in future that wants a simple way to achieve complex shadow effects check out my library here https://github.com/BluRe-CN/ComplexView
Using the library, you can change shadow colors, tweak edges and so much more. Here's an example to achieve what you seek for.
<com.blure.complexview.ComplexView
android:layout_width="400dp"
android:layout_height="600dp"
app:radius="10dp"
app:shadow="true"
app:shadowSpread="2">
<com.blure.complexview.ComplexView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:color="#fdfcfc"
app:radius="10dp" />
</com.blure.complexview.ComplexView>
To change the shadow color, use app:shadowColor="your color code".
This comment is for readers who have found this entry but are using mysql instead of oracle! on mysql you can do the following: Today
SELECT *
FROM
WHERE date(tran_date) = CURRENT_DATE()
Yesterday
SELECT *
FROM yourtable
WHERE date(tran_date) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)
i suggest in Javascript:
var item=1387843200000;
var date1=new Date(item);
and then date1 is a Date.
Your sheet is blank because your string writer in null. Here is what may help
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Here is the full code
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;
filename=FileName.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
Turn off your firewall for port 80 from any address. Turn off 443 if you need https (SSL) access. Open the configuration file (http.conf
) and find the lines that say:
Allow from 127.0.0.1
Change them to read
Allow from all
Restart the wampserver. It will now work. Enjoy!!
Combining matty-j suggestion with the snippet of the question, I ended up with this code focusing on resizing the grid after the data was loaded.
The HTML:
<div ng-grid="gridOptions" class="gridStyle"></div>
The directive:
angular.module('myApp.directives', [])
.directive('resize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
scope.getWindowDimensions = function () {
return { 'h': w.height(), 'w': w.width() };
};
scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
// resize Grid to optimize height
$('.gridStyle').height(newValue.h - 250);
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});
The controller:
angular.module('myApp').controller('Admin/SurveyCtrl', function ($scope, $routeParams, $location, $window, $timeout, Survey) {
// Retrieve data from the server
$scope.surveys = Survey.query(function(data) {
// Trigger resize event informing elements to resize according to the height of the window.
$timeout(function () {
angular.element($window).resize();
}, 0)
});
// Configure ng-grid.
$scope.gridOptions = {
data: 'surveys',
...
};
}
You likely want urllib2. It can handle things like HTTPS, cookies, and authentication. You will probably also want BeautifulSoup to help parse the HTML pages.
Try this one, if null set 0 or something
return command.ExecuteScalar() == DBNull.Value ? 0 : (double)command.ExecuteScalar();
Found this on a different forum
If you're wondering why that leading zero is important, it's because permissions are set as an octal integer, and Python automagically treats any integer with a leading zero as octal. So os.chmod("file", 484) (in decimal) would give the same result.
What you are doing is passing 664
which in octal is 1230
In your case you would need
os.chmod("/tmp/test_file", 436)
[Update] Note, for Python 3 you have prefix with 0o (zero oh). E.G, 0o666
Just modify one of the returned entities:
Customer c = (from x in dataBase.Customers
where x.Name == "Test"
select x).First();
c.Name = "New Name";
dataBase.SaveChanges();
Note, you can only update an entity (something that extends EntityObject, not something that you have projected using something like select new CustomObject{Name = x.Name}
You cannot use var
in a field, only on local variables.
But even this won't work:
Site master = Master as Site;
Because you cannot use this
in a field and Master as Site
is the same as this.Master as Site
. So just initialize the field from Page_Init
when the page is fully initialized and you can use this
:
Site master = null;
protected void Page_Init(object sender, EventArgs e)
{
master = this.Master as Site;
}
EDIT 2015 May
Disclaimer: I've taken the snippet from the answer linked below:
In addition to WebKit, as of Firefox 35 we'll be able to use the appearance
property:
Using
-moz-appearance
with thenone
value on a combobox now remove the dropdown button
So now in order to hide the default styling, it's as easy as adding the following rules on our select element:
select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
For IE 11 support, you can use [::-ms-expand
][15].
select::-ms-expand { /* for IE 11 */
display: none;
}
Old Answer
Unfortunately what you ask is not possible by using pure CSS. However, here is something similar that you can choose as a work around. Check the live code below.
div { _x000D_
margin: 10px;_x000D_
padding: 10px; _x000D_
border: 2px solid purple; _x000D_
width: 200px;_x000D_
-webkit-border-radius: 5px;_x000D_
-moz-border-radius: 5px;_x000D_
border-radius: 5px;_x000D_
}_x000D_
div > ul { display: none; }_x000D_
div:hover > ul {display: block; background: #f9f9f9; border-top: 1px solid purple;}_x000D_
div:hover > ul > li { padding: 5px; border-bottom: 1px solid #4f4f4f;}_x000D_
div:hover > ul > li:hover { background: white;}_x000D_
div:hover > ul > li:hover > a { color: red; }
_x000D_
<div>_x000D_
Select_x000D_
<ul>_x000D_
<li><a href="#">Item 1</a></li>_x000D_
<li><a href="#">Item 2</a></li>_x000D_
<li><a href="#">Item 3</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
EDIT
Here is the question that you asked some time ago. How to style a <select> dropdown with CSS only without JavaScript? As it tells there, only in Chrome and to some extent in Firefox you can achieve what you want. Otherwise, unfortunately, there is no cross browser pure CSS solution for styling a select.
var bottom = $('#bottom').position().top + $('#bottom').height();
Why use a complicated solution if a simple one works too?
.child {
white-space: normal;
}
Using DELETE with a Body is risky... I prefer this approach for List Operations over REST:
Regular Operations
GET /objects/ Gets all Objects
GET /object/ID Gets an Object with specified ID
POST /objects Adds a new Object
PUT /object/ID Adds an Object with specified ID, Updates an Object
DELETE /object/ID Deletes the object with specified ID
All Custom actions are POST
POST /objects/addList Adds a List or Array of Objects included in body
POST /objects/deleteList Deletes a List of Objects included in body
POST /objects/customQuery Creates a List based on custom query in body
If a client doesn't support your extended operations they can work in the regular way.
You can use CSS to accomplish this:
.disabled {
pointer-events: none;
cursor: default;
}
_x000D_
<a href="somelink.html" class="disabled">Some link</a>
_x000D_
Or you can use JavaScript to prevent the default action like this:
$('.disabled').click(function(e){
e.preventDefault();
})
Your where clause should have worked. I am at a loss as to why it didn't. Let me show you how I would have figured out the problem with the where clause as it might help you for the future.
When I create triggers, I start at the query window by creating a temp table called #inserted (and or #deleted) with all the columns of the table. Then I popultae it with typical values (Always multiple records and I try to hit the test cases in the values)
Then I write my triggers logic and I can test without it actually being in a trigger. In a case like your where clause not doing what was expected, I could easily test by commenting out the insert to see what the select was returning. I would then probably be easily able to see what the problem was. I assure you that where clasues do work in triggers if they are written correctly.
Once I know that the code works properly for all the cases, I global replace #inserted with inserted and add the create trigger code around it and voila, a tested trigger.
AS I said in a comment, I have a concern that the solution you picked will not work properly in a multiple record insert or update. Triggers should always be written to account for that as you cannot predict if and when they will happen (and they do happen eventually to pretty much every table.)
Dont't forget root is allowed root to login before!!!
Place the config code below in /etc/ssh/sshd_config
file.
PermitRootLogin yes
You can render your icon using the SVG Path notation.
See Google documentation for more information.
Here is a basic example:
var icon = {
path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
fillColor: '#FF0000',
fillOpacity: .6,
anchor: new google.maps.Point(0,0),
strokeWeight: 0,
scale: 1
}
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: false,
icon: icon
});
Here is a working example on how to display and scale a marker SVG icon:
Edit:
Another example here with a complex icon:
Edit 2:
And here is how you can have a SVG file as an icon:
Rename your variable name
to myname
, bacause name
is a generic property of window
and is not writable in the same window.
And replace
onclick='myfunction(\''" + name + "'\')'
With
onclick='myfunction(myname)'
Working example:
var myname = "Mathew";_x000D_
document.write('<button id="button" type="button" onclick="myfunction(myname);">click</button>');_x000D_
function myfunction(name) {_x000D_
alert(name);_x000D_
}
_x000D_
If you use kotlin, it's really simple.
In your RecyclerAdapter class
userV.invalidateRecycler()
holder.card_User.setCardBackgroundColor(Color.parseColor("#3eb1ae").withAlpha(60))
In your fragment or Activity
override fun invalidateRecycler() {
if (v1.recyclerCompanies.childCount > 0) {
v1.recyclerCompanies.childrenRecursiveSequence().iterator().forEach { card ->
if (card is CardView) {
card.setCardBackgroundColor(Color.WHITE)
}
}
}
}
NOTE: This answer is for SQL Server 2005. For SQL Server 2008 and later, there are much better methods as seen in the other answers.
You can use INSERT with SELECT UNION ALL:
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
...
Only for small datasets though, which should be fine for your 4 records.
The dumbest thing ever that will fix this error in Microsoft Excel (assuming you actually have everything else right):
Select your data and click "Borders All" in Excel (puts visual borders around your data) before saving the CSV. Sound pointless? I completely agree! However, it will fix this error. I use this trick at least three times a week.
Uri path = Uri.fromFile(file );
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path , "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent );
}
catch (ActivityNotFoundException e) {
Toast.makeText(EmptyBlindDocumentShow.this,
"No Application available to viewPDF",
Toast.LENGTH_SHORT).show();
}
}
Command mvnw
uses Maven that is by default downloaded to ~/.m2/wrapper
on the first use.
URL with Maven is specified in each project at .mvn/wrapper/maven-wrapper.properties
:
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
To update or change Maven version invoke the following (remember about --non-recursive
for multi-module projects):
./mvnw io.takari:maven:wrapper -Dmaven=3.3.9
or just modify .mvn/wrapper/maven-wrapper.properties
manually.
To generate wrapper from scratch using Maven (you need to have it already in PATH
run:
mvn io.takari:maven:wrapper -Dmaven=3.3.9
Apache Commons is generally known as a solid project. Keep in mind, though, you'll still have to send a verification email to the address if you want to ensure it's a real email, and that the owner wants it used on your site.
EDIT: There was a bug where it was too restrictive on domain, causing it to not accept valid emails from new TLDs.
This bug was resolved on 03/Jan/15 02:48 in commons-validator version 1.4.1
You can keep it disabled as desired, and then remove the disabled attribute before the form is submitted.
$('#myForm').submit(function() {
$('select').removeAttr('disabled');
});
Note that if you rely on this method, you'll want to disable it programmatically as well, because if JS is disabled or not supported, you'll be stuck with the disabled select.
$(document).ready(function() {
$('select').attr('disabled', 'disabled');
});
Oracle 11G Express Edition is now available to install on 64-bit versions of Windows.
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
System.out.println(ste);
}
I was unable to get Nanoix's perl script to work, or other curl examples I had seen, so I started looking into the api myself in python. This worked fine for small files, but large files choked past available ram so I found some other nice chunking code that uses the api's ability to partial download. Gist here: https://gist.github.com/csik/c4c90987224150e4a0b2
Note the bit about downloading client_secret json file from the API interface to your local directory.
Source$ cat gdrive_dl.py
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
"""API calls to download a very large google drive file. The drive API only allows downloading to ram
(unlike, say, the Requests library's streaming option) so the files has to be partially downloaded
and chunked. Authentication requires a google api key, and a local download of client_secrets.json
Thanks to Radek for the key functions: http://stackoverflow.com/questions/27617258/memoryerror-how-to-download-large-file-via-google-drive-sdk-using-python
"""
def partial(total_byte_len, part_size_limit):
s = []
for p in range(0, total_byte_len, part_size_limit):
last = min(total_byte_len - 1, p + part_size_limit - 1)
s.append([p, last])
return s
def GD_download_file(service, file_id):
drive_file = service.files().get(fileId=file_id).execute()
download_url = drive_file.get('downloadUrl')
total_size = int(drive_file.get('fileSize'))
s = partial(total_size, 100000000) # I'm downloading BIG files, so 100M chunk size is fine for me
title = drive_file.get('title')
originalFilename = drive_file.get('originalFilename')
filename = './' + originalFilename
if download_url:
with open(filename, 'wb') as file:
print "Bytes downloaded: "
for bytes in s:
headers = {"Range" : 'bytes=%s-%s' % (bytes[0], bytes[1])}
resp, content = service._http.request(download_url, headers=headers)
if resp.status == 206 :
file.write(content)
file.flush()
else:
print 'An error occurred: %s' % resp
return None
print str(bytes[1])+"..."
return title, filename
else:
return None
gauth = GoogleAuth()
gauth.CommandLineAuth() #requires cut and paste from a browser
FILE_ID = 'SOMEID' #FileID is the simple file hash, like 0B1NzlxZ5RpdKS0NOS0x0Ym9kR0U
drive = GoogleDrive(gauth)
service = gauth.service
#file = drive.CreateFile({'id':FILE_ID}) # Use this to get file metadata
GD_download_file(service, FILE_ID)
I have Jenkins running in Docker and connected Jenkins is using Docker socket from host machine Ubuntu 16.04 via volume to /var/run/docker.sock.
For me solution was:
1) Inside Docker container of Jenkins (docker exec -it jenkins bash
on host machine)
usermod -a -G docker jenkins
chmod 664 /var/run/docker.sock
service jenkins restart (or systemctl restart jenkins.service)
su jenkins
2) On host machine:
sudo service docker restart
664
means - read and write(but not execute) for owner and users from group.
There are a few different ways of doing this. I prefer using apply
, since it's easily extendable:
##Generate some data
dd = data.frame(a = 1:4, b= 1:0, c=0:3)
##Go through each row and determine if a value is zero
row_sub = apply(dd, 1, function(row) all(row !=0 ))
##Subset as usual
dd[row_sub,]
Update to Anvesh Saxena's answer(correct but outdated as FB App interface has changed):
In your FB App configuration you need to add a Website platform with your website's URL set. Then you can add App Domains which I set to our website's base domain (e.g. for a URL like http://www.mycoolwebsite.com
, just use mycoolwebsite.com
).
IMPORTANT: In order for this to work you'll need to be using a subdomain of your app's URL for your local development. You can do this easily by modifying your hosts file on your development computer to use a non-existent subdomain of your website such as local.mycoolwebsite.com
. Just google 'edit hosts file' for your platform (e.g. mac / windows) if you're not familiar with how to do this.
With async/await and promisification.
const crypto = require('crypto')
const randomBytes = Util.promisify(crypto.randomBytes)
const plain = (await randomBytes(24)).toString('base64').replace(/\W/g, '')
Generates something similar to VjocVHdFiz5vGHnlnwqJKN0NdeHcz8eM
like that very easily
i added 10 minutes to system date and always in preference use the Db server functions not custom one .
select to_char(sysdate + NUMTODSINTERVAL(10,'MINUTE'),'DD/MM/YYYY HH24:MI:SS') from dual;
In the first line of your JS code:
select.addEventListener('change', getSelection(this), false);
you're invoking getSelection by placing (this)
behind the function reference. That is most likely not what you want, because you're now passing the return value of that call to addEventListener, instead of a reference to the actual function itself.
In a function invoked by addEventListener
the value for this
will automatically be set to the object the listener is attached to, productLineSelect
in this case.
If that is what you want, you can just pass the function reference and this
will in this example be select
in invocations from addEventListener:
select.addEventListener('change', getSelection, false);
If that is not what you want, you'd best bind
your value for this to the function you're passing to addEventListener
:
var thisArg = { custom: 'object' };
select.addEventListener('change', getSelection.bind(thisArg), false);
The .bind
part is also a call, but this call just returns the same function we're calling bind
on, with the value for this
inside that function scope fixed to thisArg
, effectively overriding the dynamic nature of this-binding.
To get to your actual question: "How to pass parameters to function in addEventListener?"
You would have to use an additional function definition:
var globalVar = 'global';
productLineSelect.addEventListener('change', function(event) {
var localVar = 'local';
getSelection(event, this, globalVar, localVar);
}, false);
Now we pass the event object, a reference to the value of this
inside the callback of addEventListener, a variable defined and initialised inside that callback, and a variable from outside the entire addEventListener call to your own getSelection
function.
We also might again have an object of our choice to be this
inside the outer callback:
var thisArg = { custom: 'object' };
var globalVar = 'global';
productLineSelect.addEventListener('change', function(event) {
var localVar = 'local';
getSelection(event, this, globalVar, localVar);
}.bind(thisArg), false);
The following example demonstrates how to POST a JSON via WebClient.UploadString Method:
var vm = new { k = "1", a = "2", c = "3", v= "4" };
using (var client = new WebClient())
{
var dataString = JsonConvert.SerializeObject(vm);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}
Prerequisites: Json.NET library
If you have a file in your repo that it is supposed to be customized by most pullers, then rename the file to something like config.php.template
and add config.php
to your .gitignore
.
Use a changeset. You can add as many files as you like to the changeset, all at once, or over several commands; and then commit them all in one go.
this works for me:
cmake -D DBUILD_SHARED_LIBS=ON DBUILD_STATIC_LIBS=ON DBUILD_TESTS=ON ..
I figured out what went wrong. In the proxy configuration of my box, an extra http://
got prefixed to "proxy server with http".
Example..
http://http://proxy.mycollege.com
and that has created problems. Corrected that, and it works perfectly.
Thanks @WhiteCoffee and @ChrisBint for your suggestions!
I have solved this issue,
login to server computer where SQL Server is installed get you csv file on server computer and execute your query it will insert the records.
If you will give datatype compatibility issue change the datatype for that column
This works for me:
psql -h localhost -U postgres
It's incredible that nobody has said this over here. Passing a viewmodel through a base controller is a mess. We are using user claims to pass info to the layout page (for showing user data on the navbar for example). There is one more advantage. The data is stored via cookies, so there is no need to retrieve the data in each request via partials. Just do some googling "asp net identity claims".
You need to parse the string you are sending from javascript object to the JSON object
var json=$.parseJSON(data);
<table>
<thead>
<tr>
<th>Sn.</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php
$i=0;
$statement = $db->prepare("SELECT * FROM tbl_user ORDER BY name ASC");
$statement->execute();
$result = $statement->fetchColumn();
foreach($result as $row) {
$i++;
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $row['name']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
Kinda little late but I tried to extend @Tobia's answer to set the layout "horizontal" or "vertical" driven by the command argument e.g.
{"keys": ["f6"], "command": "split_pane", "args": {"split_type": "vertical"} }
Plugin code:
import sublime_plugin
class SplitPaneCommand(sublime_plugin.WindowCommand):
def run(self, split_type):
w = self.window
if w.num_groups() == 1:
if (split_type == "horizontal"):
w.run_command('set_layout', {
'cols': [0.0, 1.0],
'rows': [0.0, 0.33, 1.0],
'cells': [[0, 0, 1, 1], [0, 1, 1, 2]]
})
elif (split_type == "vertical"):
w.run_command('set_layout', {
"cols": [0.0, 0.46, 1.0],
"rows": [0.0, 1.0],
"cells": [[0, 0, 1, 1], [1, 0, 2, 1]]
})
w.focus_group(0)
w.run_command('clone_file')
w.run_command('move_to_group', {'group': 1})
w.focus_group(1)
else:
w.focus_group(1)
w.run_command('close')
w.run_command('set_layout', {
'cols': [0.0, 1.0],
'rows': [0.0, 1.0],
'cells': [[0, 0, 1, 1]]
})
Let's start with a quote from the virtual machine spec:
Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.
This may not occur - This is a hint, that there's something special about String
objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:
1: a := "one"
--> if(pool[hash("one")] == null) // true
pool[hash("one") --> "one"]
return pool[hash("one")]
2: b := "one"
--> if(pool[hash("one")] == null) // false, "one" already in pool
pool[hash("one") --> "one"]
return pool[hash("one")]
So in this case, variables a
and b
hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true
.
This is not the case if we use the constructor:
1: a := "one"
2: b := new String("one")
Again, "one"
is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false
So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).
As programmers we don't have to care much about the String pool, as long as we keep in mind:
(a == b) && (a.equals(b))
may be true
or false
(always use equals
to compare Strings)char[]
of a String (as you don't know who is actualling using that String)I could suggest a step by step approach.
C:\Program Files (x86)\GnuWin32\
. ...;C:\Program Files (x86)\GnuWin32\bin
No. It's going to be quite a big effort to port a browser environment to node.
Another approach, that I'm currently investigating for unit testing, is to create "Mock" version of jQuery that provides callbacks whenever a selector is called.
This way you could unit test your jQuery plugins without actually having a DOM. You'll still have to test in real browsers to see if your code works in the wild, but if you discover browser specific issues, you can easily "mock" those in your unit tests as well.
I'll push something to github.com/felixge once it's ready to show.