Here is the reason. Starting from Jersey 2.26, Jersey removed HK2 as a hard dependency. It created an SPI as a facade for the dependency injection provider, in the form of the InjectionManager
and InjectionManagerFactory
. So for Jersey to run, we need to have an implementation of the InjectionManagerFactory
. There are two implementations of this, which are for HK2 and CDI. The HK2 dependency is the jersey-hk2
others are talking about.
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.26</version>
</dependency>
The CDI dependency is
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-cdi2-se</artifactId>
<version>2.26</version>
</dependency>
This (jersey-cdi2-se) should only be used for SE environments and not EE environments.
Jersey made this change to allow others to provide their own dependency injection framework. They don't have any plans to implement any other InjectionManager
s, though others have made attempts at implementing one for Guice.
This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
headers);
JSONObject jsonObject = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://url", HttpMethod.POST, entity,
String.class);
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
} catch (final HttpClientErrorException httpClientErrorException) {
throw new ExternalCallBadRequestException();
} catch (HttpServerErrorException httpServerErrorException) {
throw new ExternalCallServerErrorException(httpServerErrorException);
} catch (Exception exception) {
throw new ExternalCallServerErrorException(exception);
}
ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.
Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.
Did you turn on the "Allow less secure apps" on? go to this link
https://myaccount.google.com/security#connectedapps
Take a look at the Sign-in & security -> Apps with account access menu.
You must turn the option "Allow less secure apps" ON.
If is still doesn't work try one of these:
Go to https://accounts.google.com/UnlockCaptcha , and click continue and unlock your account for access through other media/sites.
Use double quote in your password: "your password"
And change your .env file
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=xxxxxx
MAIL_ENCRYPTION=tls
because the one's you have specified in the mail.php will only be used if the value is not available in the .env file.
I managed to fix it finally. The problem is not related to HikariCP.
The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional
or enveloping all the logic in a single call to transactional service method seem to solve the problem.
If you are building a universal library and need to support the Simulator (x86_64) then build the framework for all platforms by setting Build Active Architecture Only
to No
.
Your Custom AuthenticationProvider class should be annotated with the following:
@Transactional
This will make sure the presence of the hibernate session there as well.
specifying the "antMatcher" before "authorizeRequests()" like below will restrict the authenticaiton to only those URLs specified in "antMatcher"
http.csrf().disable() .antMatcher("/apiurlneedsauth/**").authorizeRequests().
In my case, I was fetching data from database, changing some column values and updating it in database but for updating I was using the same save query which was violating primary key constraints i.e duplicate values for primary key, so I had written a separate query for updating the columns and it solved my problem..!
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private List< COrder > orders;
I think you should not rely on the implicit conversion. It is a bad practice.
Instead you should try like this:
datenum >= to_date('11/26/2013','mm/dd/yyyy')
or like
datenum >= date '2013-09-01'
This error may happen when mapping variables you defined in REST definition do not match with @PathVariable names.
Example: Suppose you defined in the REST definition
@GetMapping(value = "/{appId}", produces = "application/json", consumes = "application/json")
Then during the definition of the function, it should be
public ResponseEntity<List> getData(@PathVariable String appId)
This error may occur when you use any other variable other than defined in the REST controller definition with @PathVariable. Like, the below code will raise the error as ID is different than appId variable name:
public ResponseEntity<List> getData(@PathVariable String ID)
it looks like your custom JpaRepository method name does not match any Variable in your entity classs. Make sure your method name matches a variable in your entity class
for example: you got a variable name called "active" and your custom JpaRepository method says "findByActiveStatus" and since there is no variable called "activeStatus" it will throw"PropertyReferenceException"
Suppress the @JoinColumn(name="categoria")
on the ID field of the Categoria
class and I think it will work.
I'm answering on specific to this error code(08s01).
usually, MySql close socket connections are some interval of time that is wait_timeout defined on MySQL server-side which by default is 8hours. so if a connection will timeout after this time and the socket will throw an exception which SQLState is "08s01".
1.use connection pool to execute Query, make sure the pool class has a function to make an inspection of the connection members before it goes time_out.
2.give a value of <wait_timeout> greater than the default, but the largest value is 24 days
3.use another parameter in your connection URL, but this method is not recommended, and maybe deprecated.
I disabled avast antivirus for 10 minutes and get it working.
Class.forName("oracle.jdbc.driver.OracleDriver");
This line causes ClassNotFoundException
, because you haven't placed ojdbc14.jar
file in your lib folder of the project. or YOu haven't set the classpath
of the required jar
You need to tell it that you are using SSL:
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
In case you miss anything, here is working code:
String d_email = "[email protected]",
d_uname = "Name",
d_password = "urpassword",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "[email protected]",
m_subject = "Indoors Readable File: " + params[0].getName(),
m_text = "This message is from Indoor Positioning App. Required file(s) are attached.";
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SMTPAuthenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
try {
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
Transport transport = session.getTransport("smtps");
transport.connect(d_host, Integer.valueOf(d_port), d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (AddressException e) {
e.printStackTrace();
return false;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
You are looking at sqljdbc4.2 version like :
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
but, for sqljdbc4 version statement should be:
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
I think if you change your first version to write the correct Class.forName , your application will run.
Probably the jstl libraries are missing from your classpath/not accessible by tomcat.
You need to add at least the following jar files in your WEB-INF/lib
directory:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>teste4</groupId>
<artifactId>teste4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>bootstrap</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.7.Final</version>
</dependency>
</dependencies>
</project>
Context envContext = (Context)initContext.lookup("java:comp/env");
not:Context envContext = (Context)initContext.lookup("java:/comp/env");
In my case, I was defining a bean and autowiring it in the constructor of the same class file.
@SpringBootApplication
public class MyApplication {
private MyBean myBean;
public MyApplication(MyBean myBean) {
this.myBean = myBean;
}
@Bean
public MyBean myBean() {
return new MyBean();
}
}
My solution was to move the bean definition to another class file.
@Configuration
public CustomConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
I had a similar problem and although I made sure that referenced entities were saved first it keeps failing with the same exception. After hours of investigation it turns out that the problem was because the "version" column of the referenced entity was NULL. In my particular setup i was inserting it first in an HSQLDB(that was a unit test) a row like that:
INSERT INTO project VALUES (1,1,'2013-08-28 13:05:38','2013-08-28 13:05:38','aProject','aa',NULL,'bb','dd','ee','ff','gg','ii',NULL,'LEGACY','0','CREATED',NULL,NULL,1,'0',NULL,NULL,NULL,NULL,'0','0', NULL);
The problem of the above is the version column used by hibernate was set to null, so even if the object was correctly saved, Hibernate considered it as unsaved. When making sure the version had a NON-NULL(1 in this case) value the exception disappeared and everything worked fine.
I am putting it here in case someone else had the same problem, since this took me a long time to figure this out and the solution is completely different than the above.
I solved the issue by Changing the port no. in adrs-instances.xml file:
\JDEV_USER_HOME\system11.1.1.3.37.56.60\o.j2ee\adrs-instances.xml
MSK,
Have you tried setting a namespace declaration to your member variables like this? :
@XmlElement(required = true, namespace = "http://example.com/a")
protected String username;
@XmlElement(required = true, namespace = "http://example.com/a")
protected String password;
For our project, it solved namespace issues. We also had to create NameSpacePrefixMappers.
I just found this post: http://forum.springsource.org/showthread.php?68949-White-spaces-are-required-between-publicId-and-systemId./page2&s=c69fe19798f5a071d22eaf681ca84a56
A couple people here had success by switching the lines around in an XML file.
i Did it, just follow this tutorial. helps a lot
Is a copy from javadb (because is down)
http://informatictips.blogspot.pt/2013/09/using-message-handler-to-alter-soap.html
or
http://www.javadb.com/using-a-message-handler-to-alter-the-soap-header-in-a-web-service-client
Yes, need no network service, because Google Authenticator app won't communicate with the google server, it just keeps synced with the initital secret that your server generate(input into your phone from QR code) while the time pass.
the following property must be added in the gradle.build file
processResources {
filesMatching("**/*.properties") {
expand project.properties
}
}
Additionally, if working with Intellij, the project must be re-imported.
You perhaps use the wrong username.
I had a similar error. Ensure you're not using uppercase while logging into server.
Example: [email protected]
If you use ->setUsername('JacekPL')
, this can cause an error. Use ->setUsername('jacekpl')
instead. This solved my problem.
Update your pom.xml
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.1</version>
</dependency>
You need to close the XML with </web-app>
, not with <web-app>
.
In Java you would do something similar to:
Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
Note 'smtpS' protocol. Also socketFactory properties is no longer necessary in modern JVMs but you might need to set 'mail.smtps.auth' and 'mail.smtps.starttls.enable' to 'true' for Gmail. 'mail.smtps.debug' could be helpful too.
Even I was facing a similar error. Try below 2 steps (the first of which has been recommended here already) -
1. Add the dependencies to your pom.xml
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
jar
files in your .m2\repository\javax\<folder>\<version>\
directory.you will get the time without specifying the date format. convert the string to date using Date
object
var myDate = new Date('Mon 03-Jul-2017, 06:00 PM');
working solution:
var myDate= new Date('Mon 03-Jul-2017, 06:00 PM');_x000D_
console.log(moment(myDate).format('HH:mm')); // 24 hour format _x000D_
console.log(moment(myDate).format('hh:mm'));_x000D_
console.log(moment(myDate).format('hh:mm A'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
To search the whole computer:
gdr -PSProvider 'FileSystem' | %{ ls -r $.root} 2>$null | where { $.name -eq "httpd.exe" }
I am pretty sure this is a much less efficient command, for MANY reasons, but the simplest is your piping everything to your where-object command, when you could still use -filter "httpd.exe" and save a ton of cycles.
Also, on a lot of computers the get-psdrive is gonna grab shared drives, and I am pretty sure you wanted that to get a complete search. Most shares can be IMMENSE with regard to the sheer number of files and folders, so at the very least I would sort my drives by size, and add a check after each search to exit the loop if we locate the file. That is if you are looking for a single instance, if not the only way to save yourself the IMMENSE time sink of searching a 10TB share or two, is to comment the command and highly suggest any user who were to need to use it should limit their search as much as they can. For instance our User Profile share is 10TB, at least the one I am on is, and I can limit my search to the directory $sharedrive\users\myname and search my 116GB directory rather than the 10TB one. Too many unknowns with shares for this type of script, which is already super inefficient with regard to resources and speed.
If I was seriously considering using something like this, I would add a call to a 3rd party package and leverage a DB.
Most of the time,bootstrap project uses jQuery, so you can use jQuery.
Just get the width and height of parent with JQuery.offsetHeight()
and JQuery.offsetWidth()
, and set them to the child element with JQuery.width()
and JQuery.height()
.
If you want to make it responsive, repeat the above steps in the $(window).resize(func)
, as well.
Try this, it works for me.
^(00|\+)[1-9]{1}([0-9][\s]*){9,16}$
You can't send application/json
directly -- it has to be a parameter of a GET/POST request.
So something like
$.post(url, {json: "...json..."}, function());
Answering normajeans' question about setting default value. Create a defaults object with same properties and merge with the arguments object
If using ES6:
function yourFunction(args){
let defaults = {opt1: true, opt2: 'something'};
let params = {...defaults, ...args}; // right-most object overwrites
console.log(params.opt1);
}
Older Browsers using Object.assign(target, source):
function yourFunction(args){
var defaults = {opt1: true, opt2: 'something'};
var params = Object.assign(defaults, args) // args overwrites as it is source
console.log(params.opt1);
}
In case you have already installed the TortoiseSVN GUI and wondering how to upgrade to command line tools, here are the steps...
Refer to this image for further steps.
After completion of the command line client tools, open a command prompt and type svn help
to check the successful install.
I had this issue , When calling Generic.List like:
mylist.Select( selectFunc )
Where selectFunc is defined as Expression<Func<T, List<string>>>
. Simply changed "mylist" to be a IQuerable
instead of List
then it allowed me to use .Select
.
Another replacement would be dotPeek. JetBrains announced it as a free tool. It will probably have more features when used with their Resharper but even when used alone it works very well.
User experience is more like MSVS than a standalone disassembler. I like code reading more than in Reflector. Ctrl+T navigation suits me better too. Just synchronizing the tree with the code pane could be better.
All in all, it is still in development but very well usable already.
final has three good reasons:
Like methods, local variables and parameters need not to be declared final. As others said before, this clutters the code becoming less readable with very little efford for compiler performace optimisation, this is no real reason for most code fragments.
I think the only way to do this is to run another machine in parallel and use that machine to issue commands to your android box similar to how you would with a phone. If you have issues with the IP changing you can reserve an ip on your router and have the machine grab that one instead of asking the routers DHCP for one. This way you can ping the machine and figure out if it's done rebooting to continue the script.
just edit the function cell in the fpdf.php file, look for the line that looks like this
function cell ($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '')
{
after finding the line
write after the {
,
$txt = utf8_decode($txt);
save the file and ready, the accents and the utf8 encoding will be working :)
Probably embed into your objects an ID "tag" and use it to distinguish between objects of class A and objects of class B.
This however shows a flaw in the design. Ideally those methods in B which A doesn't have, should be part of A but left empty, and B overwrites them. This does away with the class-specific code and is more in the spirit of OOP.
I wanted to assign the values to an array. So, extending Michael Krelin's approach, I did:
read a[{1..3}] <<< $(echo 2 4 6); echo "${a[1]}|${a[2]}|${a[3]}"
which yields:
2|4|6
as expected.
With Spring Boot + Spring Data it has become quite easy:
@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {
@Autowired
MyRepository subject;
@Test
public void myTest() throws Exception {
subject.save(new MyEntity());
}
}
The solution by @heez brings up the full context, this only bring up what is needed for JPA+Transaction to work. Note that the solution above will bring up a in memory test database given that one can be found on the classpath.
Swift 4 / 5:
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.checkAction))
self.myView.addGestureRecognizer(gesture)
@objc func checkAction(sender : UITapGestureRecognizer) {
// Do what you want
}
Swift 3:
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.checkAction(sender:)))
self.myView.addGestureRecognizer(gesture)
func checkAction(sender : UITapGestureRecognizer) {
// Do what you want
}
I see you already have a answer but here is another answer, maybe even faster A simple class to pass in a List of objects and retrieve either a csv or excel or password protected zip csv or excel. https://github.com/ernst223/spread-sheet-exporter
SpreadSheetExporter spreadSheetExporter = new SpreadSheetExporter(List<Object>, "Filename");
File fileCSV = spreadSheetExporter.getCSV();
<script>_x000D_
$(document).ready(function(){_x000D_
var a =parseInt($("#a").val());_x000D_
var b =parseInt($("#b").val());_x000D_
$("#submit").on("click",function(){_x000D_
var sum = a + b;_x000D_
alert(sum);_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
This steps are all in the terminal:)->source
sudo /usr/local/mysql/support-files/mysql.server start
/usr/local/mysql/bin/mysql -v
cd ; nano .bash_profile
paste in and save:
export PATH="/usr/local/mysql/bin:$PATH"
"The first command brings you to your home directory and opens the .bash_profile file or creates a new one if it doesn’t exist, then add in the line above which adds the mysql binary path to commands that you can run. Exit the file with type “control + x” and when prompted save the change by typing “y”. Last thing to do here is to reload the shell for the above to work straight away."
source ~/.bash_profile mysql -v
"You will get the version number again, just type “q” to exit."
in your terminal type in: mysql
and then
SHOW GLOBAL VARIABLES LIKE 'PORT';
use everytime a semikolon in the mysql client (shell)!
now you know your port and where you can configure your server(in the terminal with mysql shell/client). but for a successful connection with MySQL Benchmark or an other client you have to know more. username, passwort hostname and port. after the installation the root user has no passwort so set(howtoSetPW) the passwort in terminal with mysql shell/client. and the server is running local. so type in root, yourPW, localhost and 3007. have fun!
The problem you're running into is that most background thread / worker APIs will create the thread in a Multithreaded Apartment state. The error message indicates that the control requires the thread be a Single Threaded Apartment.
You can work around this by creating a thread yourself and specifying the STA apartment state on the thread.
var t = new Thread(MyThreadStartMethod);
t.SetApartmentState(ApartmentState.STA);
t.Start();
You don't need the "eval" even. Just put a dollar sign in front of the string:
cmd="ls"
$cmd
response_json = ("{ \"response_json\":" + str(list_of_dict)+ "}").replace("\'","\"")
response_json = json.dumps(response_json)
response_json = json.loads(response_json)
Here is the complete example for previewing image before it gets upload.
HTML :
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://goo.gl/r57ze"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>
JavaScript :
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
If you want to compare based on the commit messages, you can do the following:
git fetch
git log --oneline origin/master | cut -d' ' -f2- > master_log
git log --oneline origin/branch-X | cut -d' ' -f2- > branchx_log
diff <(sort master_log) <(sort branchx_log)
Hierarchy of log4j logging levels are as follows in Highest to Lowest order :
TRACE log level provides highest logging which would be helpful to troubleshoot issues. DEBUG log level is also very useful to trouble shoot the issues.
You can also refer this link for more information about log levels : https://logging.apache.org/log4j/2.0/manual/architecture.html
Comprehension could be also convenient in this case:
# from a list
keys = ["k1", "k2"]
d = {k:None for k in keys}
# or from another dict
d1 = {"k1" : 1, "k2" : 2}
d2 = {k:None for k in d1.keys()}
d2
# {'k1': None, 'k2': None}
DECLARE @FromDate DATETIME = '1992-01-2623:59:59.000',
@ToDate DATETIME = '2016-08-10 00:00:00.000',
@Years INT, @Months INT, @Days INT, @tmpFromDate DATETIME
SET @Years = DATEDIFF(YEAR, @FromDate, @ToDate)
- (CASE WHEN DATEADD(YEAR, DATEDIFF(YEAR, @FromDate, @ToDate),
@FromDate) > @ToDate THEN 1 ELSE 0 END)
SET @tmpFromDate = DATEADD(YEAR, @Years , @FromDate)
SET @Months = DATEDIFF(MONTH, @tmpFromDate, @ToDate)
- (CASE WHEN DATEADD(MONTH,DATEDIFF(MONTH, @tmpFromDate, @ToDate),
@tmpFromDate) > @ToDate THEN 1 ELSE 0 END)
SET @tmpFromDate = DATEADD(MONTH, @Months , @tmpFromDate)
SET @Days = DATEDIFF(DAY, @tmpFromDate, @ToDate)
- (CASE WHEN DATEADD(DAY, DATEDIFF(DAY, @tmpFromDate, @ToDate),
@tmpFromDate) > @ToDate THEN 1 ELSE 0 END)
SELECT @FromDate FromDate, @ToDate ToDate,
@Years Years, @Months Months, @Days Days
Groovy accepts nearly all Java syntax, so there is a spectrum of choices, as illustrated below:
// Java syntax
Map<String,List> map1 = new HashMap<>();
List list1 = new ArrayList();
list1.add("hello");
map1.put("abc", list1);
assert map1.get("abc") == list1;
// slightly less Java-esque
def map2 = new HashMap<String,List>()
def list2 = new ArrayList()
list2.add("hello")
map2.put("abc", list2)
assert map2.get("abc") == list2
// typical Groovy
def map3 = [:]
def list3 = []
list3 << "hello"
map3.'abc'= list3
assert map3.'abc' == list3
You can add an conditional statement. If your array goes beyond index, then break and print the rest of the file.
Also to add the language to the session, I would define some constants for each language, then make sure you have the session library autoloaded in config/autoload.php, or you load it whenever you need it. Add the users desired language to the session:
$this->session->set_userdata('language', ENGLISH);
Then you can grab it anytime like this:
$language = $this->session->userdata('language');
You can do the following. Add your ggplot code after the first line of code and end with dev.off()
.
tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()
res=300
specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.
Change width
and height
in the code above depending on the desired output.
Note that this also works for other R
plots including plot
, image
, and pheatmap
.
Other file formats
In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.
this regex can help you, you should get the first group by \1 or whatever method you have in your language.
href="([^"]*)
example:
<a href="http://www.amghezi.com">amgheziName</a>
result:
http://www.amghezi.com
Using array_key_exists() on objects is Deprecated in php 7.4
Instead either isset() or property_exists() should be used
reference : php.net
You haven't created three different empty lists. You've created one empty list, and then created a new list with three references to that same empty list. To fix the problem use this code instead:
listy = [[] for i in range(3)]
Running your example code now gives the result you probably expected:
>>> listy = [[] for i in range(3)]
>>> listy[1] = [1,2]
>>> listy
[[], [1, 2], []]
>>> listy[1].append(3)
>>> listy
[[], [1, 2, 3], []]
>>> listy[2].append(1)
>>> listy
[[], [1, 2, 3], [1]]
Select * from Table name ..i.e(are you save table name in sql(TEST) k.
Select * from TEST then you will execute your project.
This can be done as below, just need to use JSON.parse
, then you can traverse through it normally with indices.
#ideally not really needed, but in case if JSON.parse is not identifiable in your module
require 'json'
#Assuming data from bitly api is stored in json_data here
json_data = '{
"errorCode": 0,
"errorMessage": "",
"results":
{
"http://www.foo.com":
{
"hash": "e5TEd",
"shortKeywordUrl": "",
"shortUrl": "http://whateverurl",
"userHash": "1a0p8G"
}
},
"statusCode": "OK"
}'
final_data = JSON.parse(json_data)
puts final_data["results"]["http://www.foo.com"]["shortUrl"]
Consider:
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
This code was adapted from Ozgrid
and as jkf points out, from Mr Excel
@kit's answer is okay, but remember to add ROUTER_PROVIDERS
to providers in the component. Then you can redirect to another page within ngOnInit
method:
import {Component, OnInit} from 'angular2/core';
import {Router, ROUTER_PROVIDERS} from 'angular2/router'
@Component({
selector: 'loginForm',
templateUrl: 'login.html',
providers: [ROUTER_PROVIDERS]
})
export class LoginComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.navigate(['./SomewhereElse']);
}
}
Try below :
DECLARE @myDateTime DATETIME
SET @myDateTime = '2013-02-02'
-- Convert to string now
SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)
Either:
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
or:
public static string ByteArrayToString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-","");
}
There are even more variants of doing it, for example here.
The reverse conversion would go like this:
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
Using Substring
is the best option in combination with Convert.ToByte
. See this answer for more information. If you need better performance, you must avoid Convert.ToByte
before you can drop SubString
.
Assuming i'm in a container with 15px padding, this is what i always use for the inner part:
width:auto;
right:15px;
left:15px;
That will stretch the inner part to whatever width it should be less the 15px either side.
First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
I found that I had to place a special z-index designation on div in a ie7 specific styelsheet:
div { z-index:10; }
For the z-index of unrelated divs, such as a nav, to show above the slider. I could not simply add a z-index to the slider div itself.
I had the same Problem. I had start my Oracle TNS Listener, then it works normally again.
The easiest way to convert an ISO-8859-1 string to UTF-8 string.
private static String convertIsoToUTF8(String example) throws UnsupportedEncodingException {
return new String(example.getBytes("ISO-8859-1"), "utf-8");
}
If we want to convert an UTF-8 string to ISO-8859-1 string.
private static String convertUTF8ToISO(String example) throws UnsupportedEncodingException {
return new String(example.getBytes("utf-8"), "ISO-8859-1");
}
Moreover, a method that converts an ISO-8859-1 string to UTF-8 string without using the constructor of class String.
public static String convertISO_to_UTF8_personal(String strISO_8859_1) {
String res = "";
int i = 0;
for (i = 0; i < strISO_8859_1.length() - 1; i++) {
char ch = strISO_8859_1.charAt(i);
char chNext = strISO_8859_1.charAt(i + 1);
if (ch <= 127) {
res += ch;
} else if (ch == 194 && chNext >= 128 && chNext <= 191) {
res += chNext;
} else if(ch == 195 && chNext >= 128 && chNext <= 191){
int resNum = chNext + 64;
res += (char) resNum;
} else if(ch == 194){
res += (char) 173;
} else if(ch == 195){
res += (char) 224;
}
}
char ch = strISO_8859_1.charAt(i);
if (ch <= 127 ){
res += ch;
}
return res;
}
}
That method is based on enconding utf-8 to iso-8859-1 of this website. Encoding utf-8 to iso-8859-1
Basically you shouldn't do exact comparisons, you should do something like this:
double a = 1.000001;
double b = 0.000001;
double c = a-b;
if (Math.abs(c-1.0) <= 0.000001) {...}
Here is an elegant library that records video in all supported browsers and supports uploading:
escapeRegExp = function(str) {
if (str == null) return '';
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
If you are using TypeScript, it is a better approach to let the compiler check for nulls and undefineds (or the possibility thereof), rather than checking for them at run-time. (If you do want to check at run-time, then as many answers indicate, just use value == null
).
Use the compile option strictNullChecks
to tell the compiler to choke on possible null or undefined values. If you set this option, and then there is a situation where you do want to allow null and undefined, you can define the type as Type | null | undefined
.
The Array.prototype.shift
method removes the first element from an array, and returns it. It modifies the original array.
var a = [1,2,3]
// [1,2,3]
a.shift()
// 1
a
//[2,3]
Technically the answer of zlovelady is preferable, but as I had only to remove items from the navigation, the approach of unsetting the not-needed navigation items in the template was the fastest/easiest way for me:
Just duplicate
app/design/frontend/base/default/template/customer/account/navigation
to
app/design/frontend/YOUR_THEME/default/template/customer/account/navigation
and unset the unneeded navigation items before the get rendered, e.g.:
<?php $_links = $this->getLinks(); ?>
<?php
unset($_links['recurring_profiles']);
?>
public static void main(String[] args) {
try {
String keystorePass = "20174";
String keyPass = "rav@789";
String alias = "TyaGi!";
InputStream keystoreStream = new FileInputStream("D:/keyFile.jks");
KeyStore keystore = KeyStore.getInstance("JCEKS");
keystore.load(keystoreStream, keystorePass.toCharArray());
Key key = keystore.getKey(alias, keyPass.toCharArray());
byte[] bt = key.getEncoded();
String s = new String(bt);
System.out.println("------>"+s);
String str12 = Base64.encodeBase64String(bt);
System.out.println("Fetched Key From JKS : " + str12);
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
System.out.println(ex);
}
}
You can install and use the pip-autoremove utility to remove a package plus unused dependencies.
# install pip-autoremove
pip install pip-autoremove
# remove "somepackage" plus its dependencies:
pip-autoremove somepackage -y
Before taking such drastic measures, quit Xcode and follow all the instructions here for cleaning out the caches:
How to Empty Caches and Clean All Targets Xcode 4
If that doesn't help, and you decide you really need a clean installation of Xcode, then, in addition to all of the stuff in that answer, trash the Xcode app itself, plus trash your ~/Library/Developer
folder and your ~/Library/Preferences/com.apple.dt.Xcode.plist
file. I think that should just about do it.
The code below creates a Documents directory and then a sub-directory for the application and saved the files to it.
public class loadDataTooDisk extends AsyncTask<String, Integer, String> {
String sdCardFileTxt;
@Override
protected String doInBackground(String... params)
{
//check to see if external storage is avalibel
checkState();
if(canW == canR == true)
{
//get the path to sdcard
File pathToExternalStorage = Environment.getExternalStorageDirectory();
//to this path add a new directory path and create new App dir (InstroList) in /documents Dir
File appDirectory = new File(pathToExternalStorage.getAbsolutePath() + "/documents/InstroList");
// have the object build the directory structure, if needed.
appDirectory.mkdirs();
//test to see if it is a Text file
if ( myNewFileName.endsWith(".txt") )
{
//Create a File for the output file data
File saveFilePath = new File (appDirectory, myNewFileName);
//Adds the textbox data to the file
try{
String newline = "\r\n";
FileOutputStream fos = new FileOutputStream (saveFilePath);
OutputStreamWriter OutDataWriter = new OutputStreamWriter(fos);
OutDataWriter.write(equipNo.getText() + newline);
// OutDataWriter.append(equipNo.getText() + newline);
OutDataWriter.append(equip_Type.getText() + newline);
OutDataWriter.append(equip_Make.getText()+ newline);
OutDataWriter.append(equipModel_No.getText()+ newline);
OutDataWriter.append(equip_Password.getText()+ newline);
OutDataWriter.append(equipWeb_Site.getText()+ newline);
//OutDataWriter.append(equipNotes.getText());
OutDataWriter.close();
fos.flush();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
return null;
}
}
This one builds the file name
private String BuildNewFileName()
{ // creates a new filr name
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
StringBuilder sb = new StringBuilder();
sb.append(today.year + ""); // Year)
sb.append("_");
sb.append(today.monthDay + ""); // Day of the month (1-31)
sb.append("_");
sb.append(today.month + ""); // Month (0-11))
sb.append("_");
sb.append(today.format("%k:%M:%S")); // Current time
sb.append(".txt"); //Completed file name
myNewFileName = sb.toString();
//Replace (:) with (_)
myNewFileName = myNewFileName.replaceAll(":", "_");
return myNewFileName;
}
Hope this helps! It took me a long time to get it working.
When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.
If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.
inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.
The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like
With ThisWorkbook.Worksheets("Template")
.Range(inputTemplateHeader).Value = NO_ENTRY
.Range(inputTemplateContent).Value = NO_ENTRY
End With
Adjust the workbook and worksheet references to fit your particular situation.
var seconds_inputs = document.getElementsByClassName('deal_left_seconds');_x000D_
var total_timers = seconds_inputs.length;_x000D_
for ( var i = 0; i < total_timers; i++){_x000D_
var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';_x000D_
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');_x000D_
var cal_seconds = seconds_inputs[i].getAttribute('value');_x000D_
_x000D_
eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');_x000D_
eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');_x000D_
}_x000D_
function timer() {_x000D_
for ( var i = 0; i < total_timers; i++) {_x000D_
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');_x000D_
_x000D_
var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);_x000D_
var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));_x000D_
var hours = Math.floor(hoursLeft / 3600);_x000D_
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));_x000D_
var minutes = Math.floor(minutesLeft / 60);_x000D_
var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;_x000D_
_x000D_
function pad(n) {_x000D_
return (n < 10 ? "0" + n : n);_x000D_
}_x000D_
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);_x000D_
document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);_x000D_
document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);_x000D_
document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);_x000D_
_x000D_
if (eval('seconds_'+ seconds_prod_id) == 0) {_x000D_
clearInterval(countdownTimer);_x000D_
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);_x000D_
} else {_x000D_
var value = eval('seconds_'+seconds_prod_id);_x000D_
value--;_x000D_
eval('seconds_' + seconds_prod_id + '= ' + value + ';');_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
var countdownTimer = setInterval('timer()', 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">_x000D_
<div class="box-wrapper">_x000D_
<div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper">_x000D_
<div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper">_x000D_
<div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper hidden-md">_x000D_
<div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>_x000D_
</div>
_x000D_
I found solution for Spring 3.1. with using @ResponseBody annotation. Here is example of controller using Json output:
@RequestMapping(value = "/getDealers", method = RequestMethod.GET,
produces = "application/json; charset=utf-8")
@ResponseBody
public String sendMobileData() {
}
Here's my effort to give a more complete answer (building on @john's answer).
The initial issue I encountered was changing the width and height of a canvas node (using styles), resulted in the contents just being "zoomed" or "shrunk." This was not the desired effect.
So, say you want to draw two rectangles of arbitrary size in a canvas that is 100px by 100px.
<canvas width="100" height="100"></canvas>
To ensure that the rectangles will not exceed the size of the canvas and therefore not be visible, you need to ensure that the canvas is big enough.
var $canvas = $('canvas'),
oldCanvas,
context = $canvas[0].getContext('2d');
function drawRects(x, y, width, height)
{
if (($canvas.width() < x+width) || $canvas.height() < y+height)
{
oldCanvas = $canvas[0].toDataURL("image/png")
$canvas[0].width = x+width;
$canvas[0].height = y+height;
var img = new Image();
img.src = oldCanvas;
img.onload = function (){
context.drawImage(img, 0, 0);
};
}
context.strokeRect(x, y, width, height);
}
drawRects(5,5, 10, 10);
drawRects(15,15, 20, 20);
drawRects(35,35, 40, 40);
drawRects(75, 75, 80, 80);
Finally, here's the jsfiddle for this: http://jsfiddle.net/Rka6D/4/ .
Used Rn222's answer and aknuds1's answer to use an ISearchContext that returns either a single element, or a list. And a minimum number of elements can be specified:
public static class SearchContextExtensions
{
/// <summary>
/// Method that finds an element based on the search parameters within a specified timeout.
/// </summary>
/// <param name="context">The context where this is searched. Required for extension methods</param>
/// <param name="by">The search parameters that are used to identify the element</param>
/// <param name="timeOutInSeconds">The time that the tool should wait before throwing an exception</param>
/// <returns> The first element found that matches the condition specified</returns>
public static IWebElement FindElement(this ISearchContext context, By by, uint timeOutInSeconds)
{
if (timeOutInSeconds > 0)
{
var wait = new DefaultWait<ISearchContext>(context);
wait.Timeout = TimeSpan.FromSeconds(timeOutInSeconds);
return wait.Until<IWebElement>(ctx => ctx.FindElement(by));
}
return context.FindElement(by);
}
/// <summary>
/// Method that finds a list of elements based on the search parameters within a specified timeout.
/// </summary>
/// <param name="context">The context where this is searched. Required for extension methods</param>
/// <param name="by">The search parameters that are used to identify the element</param>
/// <param name="timeoutInSeconds">The time that the tool should wait before throwing an exception</param>
/// <returns>A list of all the web elements that match the condition specified</returns>
public static IReadOnlyCollection<IWebElement> FindElements(this ISearchContext context, By by, uint timeoutInSeconds)
{
if (timeoutInSeconds > 0)
{
var wait = new DefaultWait<ISearchContext>(context);
wait.Timeout = TimeSpan.FromSeconds(timeoutInSeconds);
return wait.Until<IReadOnlyCollection<IWebElement>>(ctx => ctx.FindElements(by));
}
return context.FindElements(by);
}
/// <summary>
/// Method that finds a list of elements with the minimum amount specified based on the search parameters within a specified timeout.<br/>
/// </summary>
/// <param name="context">The context where this is searched. Required for extension methods</param>
/// <param name="by">The search parameters that are used to identify the element</param>
/// <param name="timeoutInSeconds">The time that the tool should wait before throwing an exception</param>
/// <param name="minNumberOfElements">
/// The minimum number of elements that should meet the criteria before returning the list <para/>
/// If this number is not met, an exception will be thrown and no elements will be returned
/// even if some did meet the criteria
/// </param>
/// <returns>A list of all the web elements that match the condition specified</returns>
public static IReadOnlyCollection<IWebElement> FindElements(this ISearchContext context, By by, uint timeoutInSeconds, int minNumberOfElements)
{
var wait = new DefaultWait<ISearchContext>(context);
if (timeoutInSeconds > 0)
{
wait.Timeout = TimeSpan.FromSeconds(timeoutInSeconds);
}
// Wait until the current context found the minimum number of elements. If not found after timeout, an exception is thrown
wait.Until<bool>(ctx => ctx.FindElements(by).Count >= minNumberOfElements);
// If the elements were successfuly found, just return the list
return context.FindElements(by);
}
}
Example usage:
var driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://localhost");
var main = driver.FindElement(By.Id("main"));
// It can be now used to wait when using elements to search
var btn = main.FindElement(By.Id("button"), 10);
btn.Click();
// This will wait up to 10 seconds until a button is found
var button = driver.FindElement(By.TagName("button"), 10)
// This will wait up to 10 seconds until a button is found, and return all the buttons found
var buttonList = driver.FindElements(By.TagName("button"), 10)
// This will wait for 10 seconds until we find at least 5 buttons
var buttonsMin = driver.FindElements(By.TagName("button"), 10, 5);
driver.Close();
The problem was that I used ajax to post the message to the server, when I used a direct link to download the file everything worked fine.
I used this other Stackoverflow Q&A material instead, it worked great for me:
I found this somewhere else. I like this answer!
SELECT [Hourly], COUNT(*) as [Count]
FROM
(SELECT dateadd(hh, datediff(hh, '20010101', [date_created]), '20010101') as [Hourly]
FROM table) idat
GROUP BY [Hourly]
Also with rounding:
extension Float
{
func format(f: String) -> String
{
return NSString(format: "%\(f)f", self)
}
mutating func roundTo(f: String)
{
self = NSString(format: "%\(f)f", self).floatValue
}
}
extension Double
{
func format(f: String) -> String
{
return NSString(format: "%\(f)f", self)
}
mutating func roundTo(f: String)
{
self = NSString(format: "%\(f)f", self).doubleValue
}
}
x = 0.90695652173913
x.roundTo(".2")
println(x) //0.91
Not gonna happen with CSS only
Inline javascript
<a href='index.html'
onmouseover='this.style.textDecoration="none"'
onmouseout='this.style.textDecoration="underline"'>
Click Me
</a>
In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:
<a href="http://www.w3.org/Style/CSS"
style="{color: blue; background: white} /* a+=0 b+=0 c+=0 */
:visited {color: green} /* a+=0 b+=1 c+=0 */
:hover {background: yellow} /* a+=0 b+=1 c+=0 */
:visited:hover {color: purple} /* a+=0 b+=2 c+=0 */
">
</a>
but it was never implemented in the release of the spec as far as I know.
http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules
Use the following selector.
$('#attached_docs [value=123]').remove();
import re
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
r'localhost|' #localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
print(re.match(regex, "http://www.example.com") is not None) # True
print(re.match(regex, "example.com") is not None) # False
Another option is to add it to the jest.config.js
file after the module.exports
definition:
process.env = Object.assign(process.env, {
VAR_NAME: 'varValue',
VAR_NAME_2: 'varValue2'
});
This way it's not necessary to define the environment variables in each .spec
file and they can be adjusted globally.
You can also set background is transparent. So the button looks like fit your icon.
<ImageButton
android:id="@+id/Button01"
android:scaleType="fitcenter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:cropToPadding="false"
android:paddingLeft="10dp"
android:background="@android:color/transparent"
android:src="@drawable/eye" />
You don't have any example code but I assume you want to do something like this?
@View({
directives: [NgClass],
styles: [`
.${TodoModel.COMPLETED} {
text-decoration: line-through;
}
.${TodoModel.STARTED} {
color: green;
}
`],
template: `<div>
<span [ng-class]="todo.status" >{{todo.title}}</span>
<button (click)="todo.toggle()" >Toggle status</button>
</div>`
})
You assign ng-class
to a variable which is dynamic (a property of a model called TodoModel
as you can guess).
todo.toggle()
is changing the value of todo.status
and there for the class of the input is changing.
This is an example for class name but actually you could do the same think for css properties.
I hope this is what you meant.
This example is taken for the great egghead tutorial here.
Swift
You should always use the system defaults and not hard coding the font name because the default font could be changed by Apple at any time.
There are a couple of system default fonts(normal, bold, italic) with different sizes(label, button, others):
let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
let font2 = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)
let font3 = UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)
beaware that the default font size depends on the target view (label, button, others)
Examples:
let labelFont = UIFont.systemFont(ofSize: UIFont.labelFontSize)
let buttonFont = UIFont.systemFont(ofSize: UIFont.buttonFontSize)
let textFieldFont = UIFont.systemFont(ofSize: UIFont.systemFontSize)
Another alternative:
def move(arr, n):
return [arr[(idx-n) % len(arr)] for idx,_ in enumerate(arr)]
String jsonStr = "{\"a\": \"A\"}";
Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
For fun, I wrote a little jQuery add-on method that will check for any one of multiple class names:
$.fn.hasAnyClass = function() {
for (var i = 0; i < arguments.length; i++) {
if (this.hasClass(arguments[i])) {
return true;
}
}
return false;
}
Then, in your example, you could use this:
if ($('html').hasAnyClass('m320', 'm768')) {
// do stuff
}
You can pass as many class names as you want.
Here's an enhanced version that also lets you pass multiple class names separated by a space:
$.fn.hasAnyClass = function() {
for (var i = 0; i < arguments.length; i++) {
var classes = arguments[i].split(" ");
for (var j = 0; j < classes.length; j++) {
if (this.hasClass(classes[j])) {
return true;
}
}
}
return false;
}
if ($('html').hasAnyClass('m320 m768')) {
// do stuff
}
Working demo: http://jsfiddle.net/jfriend00/uvtSA/
That would be the destructor(freeing up any dynamic memory)
You can force bundler to use the gems you deploy using "bundle package" and "bundle install --local"
On your development machine:
bundle install
(Installs required gems and makes Gemfile.lock)
bundle package
(Caches the gems in vendor/cache)
On the server:
bundle install --local
(--local means "use the gems from vendor/cache")
I use
SHOW CREATE TABLE mytable;
This shows you the SQL statement necessary to receate mytable
in its current form. You can see all the columns and their types (like DESC
) but it also shows you constraint information (and table type, charset, etc.).
If you are using ubuntu you can take update
sudo apt-get update
And install extension in case of php 5.6
sudo apt-get install php5.6-intl
And in case of php 7.0
sudo apt-get install php7.0-intl
And restart your apache after
sudo service apache2 restart
If you are using xampp then remove semicolon ( ; ) in xampp/php/php.ini from below line
;extension=php_intl.dll
And then restart your xampp.
If you are doing what I believe you are trying to do, you'll need something a little more like this:
table {
border-collapse: collapse;
}
table td, table th {
border: 1px solid black;
}
table tr:first-child th {
border-top: 0;
}
table tr:last-child td {
border-bottom: 0;
}
table tr td:first-child,
table tr th:first-child {
border-left: 0;
}
table tr td:last-child,
table tr th:last-child {
border-right: 0;
}
The problem is that you are setting a 'full border' around all the cells, which make it appear as if you have a border around the entire table.
Cheers.
EDIT: A little more info on those pseudo-classes can be found on quirksmode, and, as to be expected, you are pretty much S.O.L. in terms of IE support.
Adding ->getContents()
doesn't return jSON response, instead it returns as text.
You can simply use json_decode
For this problem, I do a help function like this:
const char* name(Id id) {
struct Entry {
Id id;
const char* name;
};
static const Entry entries[] = {
{ ErrorA, "ErrorA" },
{ ErrorB, "ErrorB" },
{ 0, 0 }
}
for (int it = 0; it < gui::SiCount; ++it) {
if (entries[it].id == id) {
return entries[it].name;
}
}
return 0;
}
Linear search is usually more efficient than std::map
for small collections like this.
The DateTimeFormatInfo class implements this interface, so it allows you to control the formatting of your DateTime strings.
This works in regular JavaScript:
function theTest(val) {
var answer = "";
switch( val ) {
case 1: case 2: case 3:
answer = "Low";
break;
case 4: case 5: case 6:
answer = "Mid";
break;
case 7: case 8: case 9:
answer = "High";
break;
default:
answer = "Massive or Tiny?";
}
return answer;
}
theTest(9);
you can use this too
.parent:hover * {
/* ... */
}
_x000D_
Dates in VBA are just floating point numbers, where the integer part represents the date and the fraction part represents the time. So in addition to using the Date
function as tlayton says (to get the current date) you can also cast a date value to a integer to get the date-part from an arbitrary date: Int(myDateValue)
.
You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}
As I didn't find why does this behaviour happen I have used the following code:
float myTabLayoutSize = 360;
if (DeviceInfo.getWidthDP(this) >= myTabLayoutSize ){
tabLayout.setTabMode(TabLayout.MODE_FIXED);
} else {
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
}
Basically, I have to calculate manually the width of my tabLayout and then I set the Tab Mode depending on if the tabLayout fits in the device or not.
The reason why I get the size of the layout manually is because not all the tabs have the same width in Scrollable mode, and this could provoke that some names use 2 lines as it happened to me in the example.
You can emulate it like this:
countDownLatch = {
count: 0,
check: function() {
this.count--;
if (this.count == 0) this.calculate();
},
calculate: function() {...}
};
then each async call does this:
countDownLatch.count++;
while in each asynch call back at the end of the method you add this line:
countDownLatch.check();
In other words, you emulate a count-down-latch functionality.
You can just AND the results together if they are stored as TRUE / FALSE values:
=AND(A1:D2)
Or if stored as text, use an array formula - enter the below and press Ctrl+Shift+Enter instead of Enter.
=AND(EXACT(A1:D2,"TRUE"))
I made following changes in web.config
to get the SOAP (Request/Response) Envelope. This will output all of the raw SOAP information to the file trace.log
.
<system.diagnostics>
<trace autoflush="true"/>
<sources>
<source name="System.Net" maxdatasize="1024">
<listeners>
<add name="TraceFile"/>
</listeners>
</source>
<source name="System.Net.Sockets" maxdatasize="1024">
<listeners>
<add name="TraceFile"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener"
initializeData="trace.log"/>
</sharedListeners>
<switches>
<add name="System.Net" value="Verbose"/>
<add name="System.Net.Sockets" value="Verbose"/>
</switches>
</system.diagnostics>
An example, available for POSIX compliant systems :
/*
* This program displays the names of all files in the current directory.
*/
#include <dirent.h>
#include <stdio.h>
int main(void) {
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}
Beware that such an operation is platform dependant in C.
Source : http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608
There's surprisingly simple way of reading resource by string:
ResourceNamespace.ResxFileName.ResourceManager.GetString("ResourceKey")
It's clean and elegant solution for reading resources by keys where "dot notation" cannot be used (for instance when resource key is persisted in the database).
df.replace('-', np.nan).astype("object")
This will ensure that you can use isnull()
later on your dataframe
This will work for the non-US date format (dd/MM/yyyy
):
set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%
7z a QuickBackup%backupFilename%.zip *.backup
You can use jquery numeric for numbers.
The current version does allow what you're looking for but someone has changed the code a little bit and it works:
HTML
<input class="numeric" type="text" />
Javascript
$(".numeric").numeric({ decimal : ".", negative : false, scale: 3 });
This is the whole source.
And I've prepared this fiddle so you can see how it works.
You could also use MessageFormat too
Here's a little plug if you mostly want to
select
elementoptions
, proper zindex, etc)ul
, li
generated markupsThen jquery.yaselect.js could be a better fit. Simply:
$('select').yaselect();
And the final markup is:
<div class="yaselect-wrap">
<div class="yaselect-current"><!-- current selection --></div>
</div>
<select class="yaselect-select" size="5">
<!-- your option tags -->
</select>
Check it out on github.com
^wp.*\.php$
Should do the trick.
The .*
means "any character, repeated 0 or more times". The next .
is escaped because it's a special character, and you want a literal period (".php"). Don't forget that if you're typing this in as a literal string in something like C#, Java, etc., you need to escape the backslash because it's a special character in many literal strings.
Can use getSupportActionBar()
instead of getActionBar()
method.
It all depends in what you understand as phone number. Phone numbers are country specific. The localflavors packages for several countries contains their own "phone number field". So if you are ok being country specific you should take a look at localflavor package (class us.models.PhoneNumberField
for US case, etc.)
Otherwise you could inspect the localflavors to get the maximun lenght for all countries. Localflavor also has forms fields you could use in conjunction with the country code to validate the phone number.
You could just inline a generator to filter out the null values if you want to pretend they don't exist. Of course this is assuming the null bytes are not really part of the encoding and really are some kind of erroneous artifact or bug.
with open(filepath, "rb") as f:
reader = csv.reader( (line.replace('\0','') for line in f) )
try:
for row in reader:
print 'Row read successfully!', row
except csv.Error, e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
How about the Live method?
$('.add_to_this a').live('click', function() {
alert('hello from binded function call');
});
Still, what you did about looks like it should work. There's another post that looks pretty similar.
Basically in python range(n)
iterates n
times, which is of exclusive nature that is why it does not give last value when it is being printed, we can create a function which gives
inclusive value it means it will also print last value mentioned in range.
def main():
for i in inclusive_range(25):
print(i, sep=" ")
def inclusive_range(*args):
numargs = len(args)
if numargs == 0:
raise TypeError("you need to write at least a value")
elif numargs == 1:
stop = args[0]
start = 0
step = 1
elif numargs == 2:
(start, stop) = args
step = 1
elif numargs == 3:
(start, stop, step) = args
else:
raise TypeError("Inclusive range was expected at most 3 arguments,got {}".format(numargs))
i = start
while i <= stop:
yield i
i += step
if __name__ == "__main__":
main()
In VS2013 to set up all projects to correct build tools, you can do a right click on the solution in solution explorer and choose "Retarget solution". It will change all progects (all you check with the checkbox in opened dialog), so the error will be gone.
I have found this parameter -u with read.
"-u 1" means "read from stdin"
while read -r newline; do
((i++))
read -u 1 -p "Doing $i""th file, called $newline. Write your answer and press Enter!"
echo "Processing $newline with $REPLY" # united input from two different read commands.
done <<< $(ls)
Super simple answer - solved!
my full answer here it is now built in in some oracle versions.
select group_id,
regexp_replace(
listagg(name, ',') within group (order by name)
,'([^,]+)(,\1)*(,|$)', '\1\3')
from demotable
group by group_id;
This only works if you specify the delimiter to ',' not ', ' ie works only for no spaces after the comma. If you want spaces after the comma - here is a example how.
select
replace(
regexp_replace(
regexp_replace('BBall, BBall, BBall, Football, Ice Hockey ',',\s*',',')
,'([^,]+)(,\1)*(,|$)', '\1\3')
,',',', ')
from dual
gives BBall, Football, Ice Hockey
First, run npm install expo-linear-gradient --save
You don't need to use an animated tag, but this is what I was using in my code.
inside colors={[ put your gradient colors ]}
then you can use something like this:
import { LinearGradient } from "expo-linear-gradient";
import { Animated } from "react-native";
<AnimatedLinearGradient
colors={["rgba(255,255,255, 0)", "rgba(255,255,255, 1)"]}
style={{ your styles go here }}/>
const AnimatedLinearGradient = Animated.createAnimatedComponent(LinearGradient);
Replaced the reader declaration with this one and now it works!
Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)
Encoding.Default represents the ANSI code page that is set under Windows Control Panel.
Just in case someone is working with Eclipse
Windows 8.1 OS | Eclipse Idle Luna
Declare top level variable private String username
Eclipse kindly generate a warning on the left of your screen click that warning and couple of suggestions show up, then select generate.
i created a custom dialog API. check it out here https://github.com/MarkMyWord03/CustomDialog. It supports message and confirmation box. input and option dialog just like in joptionpane will be implemented soon.
Sample Error Dialog from CUstomDialog API: CustomDialog Error Message
If you want to get values in Javascript on frontend, you can use the native way to do it by using :
document.getElementsByName("movie")[0].value;
Where "movie"
is the name of your input
<input type="text" name="movie">
If you want to get it on angular.js controller, you can use;
$scope.movie
I was experienced this case; I need the react/redux site that should be working perfectly in production.
but there was a 'strict mode'; Shouldn't lunch it with these commands.
yarn global add serve
serve -s build
Should working with only click the build/index.html file. When I used fontawesome with npm font-awesome, it was working in development mode but not working in the 'strict mode'.
Here is my solution:
public/css/font-awesome.min.css
public/fonts/font-awesome.eot
*** other different types of files(4) ***
*** I copied these files for node_module/font-awesome ***
*** after copied then can delete the font-awesome from package.json ***
in public/index.html
<link rel="stylesheet" href="%PUBLIC_URL%/css/font-awesome.min.css">
After all of above steps, the fontawesome works NICELY!!!
I am sorry that your concluding question is not that clear but you are wrong from the very first line. The variable data is an Object not an Array
To access the attributes of an object is pretty easy:
alert(data.second);
But, if this does not completely answer your question, please clarify it and post back.
Thanks !
First the computer looks up the destination host. If it exists in local DNS cache, it uses that information. Otherwise, DNS querying is performed until the IP address is found.
Then, your browser opens a TCP connection to the destination host and sends the request according to HTTP 1.1 (or might use HTTP 1.0, but normal browsers don't do it any more).
The server looks up the required resource (if it exists) and responds using HTTP protocol, sends the data to the client (=your browser)
The browser then uses HTML parser to re-create document structure which is later presented to you on screen. If it finds references to external resources, such as pictures, css files, javascript files, these are is delivered the same way as the HTML document itself.
As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]}
are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".
{16{a[15]}}
is the same as
{
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}
In bit-blasted form,
assign result = {{16{a[15]}}, {a[15:0]}};
is the same as:
assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];
cursor are used because in sub query we can fetch record row by row so we use cursor to fetch records
Example of cursor:
DECLARE @eName varchar(50), @job varchar(50)
DECLARE MynewCursor CURSOR -- Declare cursor name
FOR
Select eName, job FROM emp where deptno =10
OPEN MynewCursor -- open the cursor
FETCH NEXT FROM MynewCursor
INTO @eName, @job
PRINT @eName + ' ' + @job -- print the name
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM MynewCursor
INTO @ename, @job
PRINT @eName +' ' + @job -- print the name
END
CLOSE MynewCursor
DEALLOCATE MynewCursor
OUTPUT:
ROHIT PRG
jayesh PRG
Rocky prg
Rocky prg
Everytime the size of the string is undetermined at compile time you have to allocate memory with malloc (or some equiviallent method). In your case you know the size of your strings at compile time (sizeof("something") and sizeof("something else")).
Add android:hardwareAccelerated="true" in your manifests file like below it works for me
<activity
android:name=".activity.MyCardViewActivity"
android:hardwareAccelerated="true"></activity>
There is also a way you can remove some old images from repository just based on the date when it was created.
To do that enter your docker registry container and get the list of manifest's revisions for some specific repository:
ls -latr /var/lib/registry/docker/registry/v2/repositories/YOUR_REPO/_manifests/revisions/sha256/
The output then may be used within the request (with sha256 prefix):
curl -v --silent -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X DELETE http://DOCKER_REGISTRY_HOST:5000/v2/YOUR_REPO/manifests/sha256:OUTPUT_LINE
And of course do not forget to execute 'garbage-collect' command after that:
bin/registry garbage-collect /etc/docker/registry/config.yml
As this is an old question, and Django techniques must have changed significantly since, this answer reflects Django version 1.4, and is most likely applicable for v 1.5.
Django by default uses relational databases; you should make use of 'em. Map friendships to database relations (foreign key constraints) with the use of ManyToManyField. Doing so allows you to use RelatedManagers for friendlists, which use smart querysets. You can use all available methods such as filter
or values_list
.
Using ManyToManyField
relations and properties:
class MyDjangoClass(models.Model):
name = models.CharField(...)
friends = models.ManyToManyField("self")
@property
def friendlist(self):
# Watch for large querysets: it loads everything in memory
return list(self.friends.all())
You can access a user's friend list this way:
joseph = MyDjangoClass.objects.get(name="Joseph")
friends_of_joseph = joseph.friendlist
Note however that these relations are symmetrical: if Joseph is a friend of Bob, then Bob is a friend of Joseph.
i got the same problem so tried so many things but finally this is the solution.
import time
print (time.strftime("%d/%m/%Y"))
You can revert your
rails g/generate controller/model/migration xxx
output by using:
rails d/destroy controller/model/migration xxx
IF "%~1"=="" GOTO :Usage
~ will de-quote %1 if %1 itself is quoted.
" " will protect from special characters passed. for example calling the script with &ping
NSString * formattedname;
NSString * firstname;
NSString * middlename;
NSString * lastname;
firstname = @"My First Name";
middlename = @"My Middle Name";
lastname = @"My Last Name";
formattedname = [NSString stringWithFormat:@"My Full Name: %@ %@ %@", firstname, middlename, lastname];
NSLog(@"\n\nHere is the Formatted Name:\n%@\n\n", formattedname);
/*
Result:
Here is the Formatted Name:
My Full Name: My First Name My Middle Name My Last Name
*/
after trying a lot of time...
task scheduler : powershell.exe -noexit & .\your_script.ps1
be sure to put your script in this folder : windows\system32
good luck !
If your host is using suPHP, you can try creating a php.ini
file in the same folder as the script and adding:
allow_url_fopen = On
(you can determine this by creating a file and checking which user it was created under: if you, it's suPHP, if "apache/nobody" or not you, then it's a normal PHP mode. You can also make a script
<?php
echo `id`;
?>
To give the same information, assuming shell_exec
is not a disabled function)
The reason it doesn't work in Safari is because you're using attribute syntax. This will work fine though:
script_tag.addEventListener('error', function(){/*...*/}, true);
...except in IE.
If you want to check the script executed successfully, just set a variable using that script and check for it being set in the outer code.
I've had the same problem and stash, hard reset, clean or even all of them was still leaving changes behind. What turned out to be the problem was the x file mode that was not set properly by git. This is a "known issue" with git for windows. The local changes show in gitk and git status as old mode 100755 new mode 100644, without any actual file differences.
The fix is to ignore the file mode:
git config core.filemode false
I think this thread may be helpful: http://forums.macosxhints.com/archive/index.php/t-70973.html
To paraphrase, you can rename it with the .command extension or create an AppleScript to run the shell.
tl;dr — There's a summary at the end and headings in the answer to make it easier to find the relevant parts. Reading everything is recommended though as it provides useful background for understanding the why that makes seeing how the how applies in different circumstances easier.
This is the Same Origin Policy. It is a security feature implemented by browsers.
Your particular case is showing how it is implemented for XMLHttpRequest (and you'll get identical results if you were to use fetch), but it also applies to other things (such as images loaded onto a <canvas>
or documents loaded into an <iframe>
), just with slightly different implementations.
(Weirdly, it also applies to CSS fonts, but that is because found foundries insisted on DRM and not for the security issues that the Same Origin Policy usually covers).
The standard scenario that demonstrates the need for the SOP can be demonstrated with three characters:
https://www.[website].com/
in your example)http://localhost:4300
in your example)Alice is logged into Bob's site and has some confidential data there. Perhaps it is a company intranet (accessible only to browsers on the LAN), or her online banking (accessible only with a cookie you get after entering a username and password).
Alice visits Mallory's website which has some JavaScript that causes Alice's browser to make an HTTP request to Bob's website (from her IP address with her cookies, etc). This could be as simple as using XMLHttpRequest
and reading the responseText
.
The browser's Same Origin Policy prevents that JavaScript from reading the data returned by Bob's website (which Bob and Alice don't want Mallory to access). (Note that you can, for example, display an image using an <img>
element across origins because the content of the image is not exposed to JavaScript (or Mallory) … unless you throw canvas into the mix in which case you will generate a same-origin violation error).
For any given URL it is possible that the SOP is not needed. A couple of common scenarios where this is the case are:
… but the browser has no way of knowing if either of the above are true, so trust is not automatic and the SOP is applied. Permission has to be granted explicitly before the browser will give the data it was given to a different website.
Browser extensions*
, the Network tab in browser developer tools and applications like Postman are installed software. They aren't passing data from one website to the JavaScript belonging to a different website just because you visited that different website. Installing software usually takes a more conscious choice.
There isn't a third party (Mallory) who is considered a risk.
*
Browser extensions do need to be written carefully to avoid cross-origin issues. See the Chrome documentation for example.
There are a number of circumstances where Mallory's site can cause a browser to fetch data from a third party and display it (e.g. by adding an <img>
element to display an image). It isn't possible for Mallory's JavaScript to read the data in that resource though, only Alice's browser and Bob's server can do that, so it is still secure.
The Access-Control-Allow-Origin
HTTP response header referred to in the error message is part of the CORS standard which allows Bob to explicitly grant permission to Mallory's site to access the data via Alice's browser.
A basic implementation would just include:
Access-Control-Allow-Origin: *
… in the response headers to permit any website to read the data.
Access-Control-Allow-Origin: http://example.com/
… would allow only a specific site to access it, and Bob can dynamically generate that based on the Origin
request header to permit multiple, but not all, sites to access it.
The specifics of how Bob sets that response header depend on Bob's HTTP server and/or server-side programming language. There is a collection of guides for various common configurations that might help.
NB: Some requests are complex and send a preflight OPTIONS request that the server will have to respond to before the browser will send the GET/POST/PUT/Whatever request that the JS wants to make. Implementations of CORS that only add Access-Control-Allow-Origin
to specific URLs often get tripped up by this.
Obviously granting permission via CORS is something Bob would only do only if either:
There is no standard mechanism for Mallory to add this header because it has to come from Bob's website, which she does not control.
If Bob is running a public API then there might be a mechanism to turn on CORS (perhaps by formatting the request in a certain way, or a config option after logging into a Developer Portal site for Bob's site). This will have to be a mechanism implemented by Bob though. Mallory could read the documentation on Bob's site to see if something is available, or she could talk to Bob and ask him to implement CORS.
Some cross origin requests are preflighted.
This happens when (roughly speaking) you try to make a cross-origin request that:
enctype
).In these cases then the rest of this answer still applies but you also need to make sure that the server can listen for the preflight request (which will be OPTIONS
(and not GET
, POST
or whatever you were trying to send) and respond to it with the right Access-Control-Allow-Origin
header but also Access-Control-Allow-Methods
and Access-Control-Allow-Headers
to allow your specific HTTP methods or headers.
Sometimes people make mistakes when trying to construct Ajax requests, and sometimes these trigger the need for a preflight. If the API is designed to allow cross-origin requests, but doesn't require anything that would need a preflight, then this can break access.
Common mistakes that trigger this include:
Access-Control-Allow-Origin
and other CORS response headers on the request. These don't belong on the request, don't do anything helpful (what would be the point of a permissions system where you could grant yourself permission?), and must appear only on the response.Content-Type: application/json
header on a GET request that has no request body to describe the content of (typically when the author confuses Content-Type
and Accept
).In either of these cases, removing the extra request header will often be enough to avoid the need for a preflight (which will solve the problem when communicating with APIs that support simple requests but not preflighted requests).
Sometimes you need to make an HTTP request, but you don't need to read the response. e.g. if you are posting a log message to the server for recording.
If you are using the fetch
API (rather than XMLHttpRequest
), then you can configure it to not try to use CORS.
Note that this won't let you do anything that you require CORS to do. You will not be able to read the response. You will not be able to make a request that requires a preflight.
It will let you make a simple request, not see the response, and not fill the Developer Console with error messages.
How to do it is explained by the Chrome error message given when you make a request using fetch
and don't get permission to view the response with CORS:
Access to fetch at '
https://example.com/
' from origin 'https://example.net
' has been blocked by CORS policy: No 'Access-Control-Allow-Origin
' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Thus:
fetch("http://example.com", { mode: "no-cors" });
Bob could also provide the data using a hack like JSONP which is how people did cross-origin Ajax before CORS came along.
It works by presenting the data in the form of a JavaScript program which injects the data into Mallory's page.
It requires that Mallory trust Bob not to provide malicious code.
Note the common theme: The site providing the data has to tell the browser that it is OK for a third party site to access the data it is sending to the browser.
Since JSONP works by appending a <script>
element to load the data in the form of a JavaScript program which calls a function already in the page, attempting to use the JSONP technique on a URL which returns JSON will fail — typically with a CORB error — because JSON is not JavaScript.
If the HTML document the JS runs in and the URL being requested are on the same origin (sharing the same scheme, hostname, and port) then they Same Origin Policy grants permission by default. CORS is not needed.
Mallory could use server-side code to fetch the data (which she could then pass from her server to Alice's browser through HTTP as usual).
It will either:
That server-side code could be written & hosted by a third party (such as CORS Anywhere). Note the privacy implications of this: The third party can monitor who proxies what across their servers.
Bob wouldn't need to grant any permissions for that to happen.
There are no security implications here since that is just between Mallory and Bob. There is no way for Bob to think that Mallory is Alice and to provide Mallory with data that should be kept confidential between Alice and Bob.
Consequently, Mallory can only use this technique to read public data.
Do note, however, that taking content from someone else's website and displaying it on your own might be a violation of copyright and open you up to legal action.
As noted in the section "Why the Same Origin Policy only applies to JavaScript in a web page", you can avoid the SOP by not writing JavaScript in a webpage.
That doesn't mean you can't continue to use JavaScript and HTML, but you could distribute it using some other mechanism, such as Node-WebKit or PhoneGap.
It is possible for a browser extension to inject the CORS headers in the response before the Same Origin Policy is applied.
These can be useful for development, but are not practical for a production site (asking every user of your site to install a browser extension that disables a security feature of their browser is unreasonable).
They also tend to work only with simple requests (failing when handling preflight OPTIONS requests).
Having a proper development environment with a local development server is usually a better approach.
Note that SOP / CORS do not mitigate XSS, CSRF, or SQL Injection attacks which need to be handled independently.
Though I'm usually against it (though in this case it seems that you have a genuine reason), have you tried providing any query hints on the SP version of the query? If SQL Server is preparing a different execution plan in those two instances, can you use a hint to tell it what index to use, so that the plan matches the first one?
For some examples, you can go here.
EDIT: If you can post your query plan here, perhaps we can identify some difference between the plans that's telling.
SECOND: Updated the link to be SQL-2000 specific. You'll have to scroll down a ways, but there's a second titled "Table Hints" that's what you're looking for.
THIRD: The "Bad" query seems to be ignoring the [IX_Openers_SessionGUID] on the "Openers" table - any chance adding an INDEX hint to force it to use that index will change things?
I faced the same issue in my scenario as follow:
I created textbook table first with
create table textbook(txtbk_isbn varchar2(13)
primary key,txtbk_title varchar2(40),
txtbk_author varchar2(40) );
Then chapter table:
create table chapter(txtbk_isbn varchar2(13),chapter_title varchar2(40),
constraint pk_chapter primary key(txtbk_isbn,chapter_title),
constraint chapter_txtbook foreign key (txtbk_isbn) references textbook (txtbk_isbn));
Then topic table:
create table topic(topic_id varchar2(20) primary key,topic_name varchar2(40));
Now when I wanted to create a relationship called chapter_topic between chapter (having composite primary key) and topic (having single column primary key), I faced issue with following query:
create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20),
primary key (txtbk_isbn, chapter_title, topic_id),
foreign key (txtbk_isbn) references textbook(txtbk_isbn),
foreign key (chapter_title) references chapter(chapter_title),
foreign key (topic_id) references topic (topic_id));
The solution was to refer to composite foreign key as below:
create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20),
primary key (txtbk_isbn, chapter_title, topic_id),
foreign key (txtbk_isbn, chapter_title) references chapter(txtbk_isbn, chapter_title),
foreign key (topic_id) references topic (topic_id));
Thanks to APC post in which he mentioned in his post a statement that:
Common reasons for this are
- the parent lacks a constraint altogether
- the parent table's constraint is a compound key and we haven't referenced all the columns in the foreign key statement.
- the referenced PK constraint exists but is DISABLED
Save any variable that want to be shared as one object. Then pass it to loaded module so it could access the variable through object reference..
// main.js
var myModule = require('./module.js');
var shares = {value:123};
// Initialize module and pass the shareable object
myModule.init(shares);
// The value was changed from init2 on the other file
console.log(shares.value); // 789
On the other file..
// module.js
var shared = null;
function init2(){
console.log(shared.value); // 123
shared.value = 789;
}
module.exports = {
init:function(obj){
// Save the shared object on current module
shared = obj;
// Call something outside
init2();
}
}
This CSS seems to work in Safari and Chrome:
div#div2
{
-webkit-transform:rotate(90deg); /* Chrome, Safari, Opera */
transform:rotate(90deg); /* Standard syntax */
}
and in the body:
<div id="div2"><img src="image.jpg" ></div>
But this (and the .rotate90 example above) pushes the rotated image higher up on the page than if it were un-rotated. Not sure how to control placement of the image relative to text or other rotated images.
In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are not inherited, are non-virtual.
For Swift 3
func stringToDate(_ str: String)->Date{
let formatter = DateFormatter()
formatter.dateFormat="yyyy-MM-dd hh:mm:ss Z"
return formatter.date(from: str)!
}
func dateToString(_ str: Date)->String{
var dateFormatter = DateFormatter()
dateFormatter.timeStyle=DateFormatter.Style.short
return dateFormatter.string(from: str)
}
Use @Deprecated
on method. Don't forget about clarifying javadoc field:
/**
* Does some thing in old style.
*
* @deprecated use {@link #new()} instead.
*/
@Deprecated
public void old() {
// ...
}
This is the best way which worked for me Execute this Command:-
$(dirname $(readlink $(which javac)))/java_home
It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of .
or ..
is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments .
and ..
”, without clarifying whether they match .
and ..
before or after pct-encoding.
Personally I find Firefox's interpretation that %2E
does not mean .
most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only .
or ..
.
I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F
, %00
and %5C
sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.
You can try this simple code with the features of ucwords in PHP.
function ucWords(text) {
return text.split(' ').map((txt) => (txt.substring(0, 1).toUpperCase() + txt.substring(1, txt.length))).join(' ');
}
ucWords('hello WORLD');
It will keep the Upper Cases unchanged.
The most effective one liner that
thisClass
on an element that has class="thisClass-suffix"
.function hasClass( target, className ) {
return new RegExp('(\\s|^)' + className + '(\\s|$)').test(target.className);
}
The full list is:
DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)
See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html
They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):
db 0x55 ; just the byte 0x55
db 0x55,0x56,0x57 ; three bytes in succession
db 'a',0x55 ; character constants are OK
db 'hello',13,10,'$' ; so are string constants
dw 0x1234 ; 0x34 0x12
dw 'A' ; 0x41 0x00 (it's just a number)
dw 'AB' ; 0x41 0x42 (character constant)
dw 'ABC' ; 0x41 0x42 0x43 0x00 (string)
dd 0x12345678 ; 0x78 0x56 0x34 0x12
dq 0x1122334455667788 ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
ddq 0x112233445566778899aabbccddeeff00
; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
do 0x112233445566778899aabbccddeeff00 ; same as previous
dd 1.234567e20 ; floating-point constant
dq 1.234567e20 ; double-precision float
dt 1.234567e20 ; extended-precision float
DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.
you should use the CSV module for sure , but the chances are , you need to write unicode . For those Who need to write unicode , this is the class from example page , that you can use as a util module:
import csv, codecs, cStringIO
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class UnicodeReader:
"""
A CSV reader which will iterate over lines in the CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
row = self.reader.next()
return [unicode(s, "utf-8") for s in row]
def __iter__(self):
return self
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
Is the drive E a mapped drive? Then, it can be created by another account other than the user account. This may be the cause of the error.
If you have a project created in Swift 4 and then added Objective-C files, do it like this:
@objcMembers
public class MyModel: NSObject {
var someFlag = false
func doSomething() {
print("doing something")
}
}
Reference: https://useyourloaf.com/blog/objc-warnings-upgrading-to-swift-4/
m2e 1.7 introduces a new syntax for lifecycle mapping metadata that doesn't cause this warning anymore:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<!-- This executes the goal in Eclipse on project import.
Other options like are available, eg ignore. -->
<?m2e execute?>
<phase>generate-sources</phase>
<goals><goal>add-source</goal></goals>
<configuration>
<sources>
<source>src/bootstrap/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
If you want to use socket.io together with php this may be your answer!
project website:
they are also on github:
https://github.com/wisembly/elephant.io
Elephant.io provides a socket.io client fully written in PHP that should be usable everywhere in your project.
It is a light and easy to use library that aims to bring some real-time functionality to a PHP application through socket.io and websockets for actions that could not be done in full javascript.
example from the project website (communicate with websocket server through php)
php server
use ElephantIO\Client as Elephant;
$elephant = new Elephant('http://localhost:8000', 'socket.io', 1, false, true, true);
$elephant->init();
$elephant->send(
ElephantIOClient::TYPE_EVENT,
null,
null,
json_encode(array('name' => 'foo', 'args' => 'bar'))
);
$elephant->close();
echo 'tryin to send `bar` to the event `foo`';
socket io server
var io = require('socket.io').listen(8000);
io.sockets.on('connection', function (socket) {
console.log('user connected!');
socket.on('foo', function (data) {
console.log('here we are in action event and data is: ' + data);
});
});
I came across this issue yesterday, but none of the solutions here worked exactly, however they did point me in the right direction.
Our application is a workflow tool written in C# and, overly simplified, has several stored procedures on the database, as well as a table of metadata about each parameter used by each stored procedure (name, order, data type, size, etc), allowing us to create as many new stored procedures as we need without having to change the C#.
Analysis of the problem showed that our code was setting all the correct parameters on the SqlCommand
object, however once it was executed, it threw the same error as the OP got.
Further analysis revealed that some parameters had a value of null
. I therefore must draw the conclusion that SqlCommand
objects ignore any SqlParameter
object in their .Parameters
collection with a value of null
.
There are two solutions to this problem that I found.
In our stored procedures, give a default value to each parameter, so from @Parameter int
to @Parameter int = NULL
(or some other default value as required).
In our code that generates the individual SqlParameter
objects, assigning DBNull.Value
instead of null
where the intended value is a SQL NULL
does the trick.
The original coder has moved on and the code was originally written with Solution 1 in mind, and having weighed up the benefits of both, I think I'll stick with Solution 1. It's much easier to specify a default value for a specific stored procedure when writing it, rather than it always being NULL
as defined in the code.
Hope that helps someone.
If you use the HtmlUnitDriver
, you can set request headers by modifying the WebClient
, like so:
final case class Header(name: String, value: String)
final class HtmlUnitDriverWithHeaders(headers: Seq[Header]) extends HtmlUnitDriver {
super.modifyWebClient {
val client = super.getWebClient
headers.foreach(h => client.addRequestHeader(h.name, h.value))
client
}
}
The headers will then be on all requests made by the web browser.
exec 3>&1 1>>${LOG_FILE} 2>&1
would send stdout and stderr output into the log file, but would also leave you with fd 3 connected to the console, so you can do
echo "Some console message" 1>&3
to write a message just to the console, or
echo "Some console and log file message" | tee /dev/fd/3
to write a message to both the console and the log file - tee
sends its output to both its own fd 1 (which here is the LOG_FILE
) and the file you told it to write to (which here is fd 3, i.e. the console).
Example:
exec 3>&1 1>>${LOG_FILE} 2>&1
echo "This is stdout"
echo "This is stderr" 1>&2
echo "This is the console (fd 3)" 1>&3
echo "This is both the log and the console" | tee /dev/fd/3
would print
This is the console (fd 3)
This is both the log and the console
on the console and put
This is stdout
This is stderr
This is both the log and the console
into the log file.
I had the same error and the problem is that I had not correctly installed Composer.
I am using Windows and I installed Composer-Setup.exe
from getcomposer.org and when you have more than one version of PHP installed you must select the version that you are running at this point of the installation
The original question is about Bootstrap 3 and that supports IE8 and 9 so Flexbox would be the best option but it's not part of my answer due the lack of support, see http://caniuse.com/#feat=flexbox and toggle the IE box. Pretty bad, eh?
1. Display-table: You can muck around with turning the row into a display:table and the col- into display:table-cell. It works buuuut the limitations of tables are there, among those limitations are the push and pull and offsets won't work. Plus, I don't know where you're using this -- at what breakpoint. You should make the image full width and wrap it inside another container to put the padding on there. Also, you need to figure out the design on mobile, this is for 768px and up. When I use this, I redeclare the sizes and sometimes I stick importants on them because tables take on the width of the content inside them so having the widths declared again helps this. You will need to play around. I also use a script but you have to change the less files to use it or it won't work responsively.
.row.table-row > [class*="col-"].custom {
background-color: lightgrey;
text-align: center;
}
@media (min-width: 768px) {
img.img-fluid {width:100%;}
.row.table-row {display:table;width:100%;margin:0 auto;}
.row.table-row > [class*="col-"] {
float:none;
float:none;
display:table-cell;
vertical-align:top;
}
.row.table-row > .col-sm-11 {
width: 91.66666666666666%;
}
.row.table-row > .col-sm-10 {
width: 83.33333333333334%;
}
.row.table-row > .col-sm-9 {
width: 75%;
}
.row.table-row > .col-sm-8 {
width: 66.66666666666666%;
}
.row.table-row > .col-sm-7 {
width: 58.333333333333336%;
}
.row.table-row > .col-sm-6 {
width: 50%;
}
.col-sm-5 {
width: 41.66666666666667%;
}
.col-sm-4 {
width: 33.33333333333333%;
}
.row.table-row > .col-sm-3 {
width: 25%;
}
.row.table-row > .col-sm-2 {
width: 16.666666666666664%;
}
.row.table-row > .col-sm-1 {
width: 8.333333333333332%;
}
}
HTML
<div class="container">
<div class="row table-row">
<div class="col-sm-4 custom">
100% height to make equal to ->
</div>
<div class="col-sm-8 image-col">
<img src="http://placehold.it/600x400/B7AF90/FFFFFF&text=image+1" class="img-fluid">
</div>
</div>
</div>
.content {
text-align: center;
padding: 10px;
background: #ccc;
}
@media (min-width:768px) {
.my-row {
position: relative;
height: 100%;
border: 1px solid red;
overflow: hidden;
}
.img-fluid {
width: 100%
}
.row.my-row > [class*="col-"] {
position: relative
}
.background {
position: absolute;
padding-top: 200%;
left: 0;
top: 0;
width: 100%;
background: #ccc;
}
.content {
position: relative;
z-index: 1;
width: 100%;
text-align: center;
padding: 10px;
}
}
HTML
<div class="container">
<div class="row my-row">
<div class="col-sm-6">
<div class="content">
This is inside a relative positioned z-index: 1 div
</div>
<div class="background"><!--empty bg-div--></div>
</div>
<div class="col-sm-6 image-col">
<img src="http://placehold.it/200x400/777777/FFFFFF&text=image+1" class="img-fluid">
</div>
</div>
</div>
You could use the PECL extension
runkit_function_redefine
— Replace a function definition with a new implementation but that is bad practise in my opinion. You are using functions, but check out the Decorator design pattern. Can borrow the basic idea from it.
You could use the concrete class LinkedList
instead of the general interface List
. Then you have a descendingIterator
for iterating with the reverse direction.
LinkedList<String > linkedList;
for( Iterator<String > it = linkedList.descendingIterator(); it.hasNext(); ) {
String text = it.next();
}
Don't know why there is no descendingIterator
with ArrayList
...
<div class="author_">Lord Byron</div>
.author_ { font-family: 'Playfair Display', serif; font-size: 1.25em; font-weight: 700;letter-spacing: 0.25em; font-style: italic;_x000D_
position:relative;_x000D_
margin-top: -0.5em;_x000D_
color: black;_x000D_
z-index:1;_x000D_
overflow:hidden;_x000D_
text-align:center;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
.author_:after{_x000D_
left:20px;_x000D_
margin:0 -100% 0 0;_x000D_
display: inline-block;_x000D_
height: 10px;_x000D_
content: url(data:image/svg+xml,%0A%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22120px%22%20height%3D%2220px%22%20viewBox%3D%220%200%201200%20200%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%0A%20%20%3Cpath%20stroke%3D%22black%22%20stroke-width%3D%223%22%20fill%3D%22none%22%20d%3D%22M1145%2085c17%2C7%208%2C24%20-4%2C29%20-12%2C4%20-40%2C6%20-48%2C-8%20-9%2C-15%209%2C-34%2026%2C-42%2017%2C-7%2045%2C-6%2062%2C2%2017%2C9%2019%2C18%2020%2C27%201%2C9%200%2C29%20-27%2C52%20-28%2C23%20-52%2C34%20-102%2C33%20-49%2C0%20-130%2C-31%20-185%2C-50%20-56%2C-18%20-74%2C-21%20-96%2C-23%20-22%2C-2%20-29%2C-2%20-56%2C7%20-27%2C8%20-44%2C17%20-44%2C17%20-13%2C5%20-15%2C7%20-40%2C16%20-25%2C9%20-69%2C14%20-120%2C11%20-51%2C-3%20-126%2C-23%20-181%2C-32%20-54%2C-9%20-105%2C-20%20-148%2C-23%20-42%2C-3%20-71%2C1%20-104%2C5%20-34%2C5%20-65%2C15%20-98%2C22%22%2F%3E%0A%3C%2Fsvg%3E%0A);_x000D_
}_x000D_
.author_:before {_x000D_
right:20px;_x000D_
margin:0 0 0 -100%;_x000D_
display: inline-block;_x000D_
height: 10px;_x000D_
content: url(data:image/svg+xml,%0A%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22120px%22%20height%3D%2220px%22%20viewBox%3D%220%200%201200%20130%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%0A%20%20%3Cpath%20stroke%3D%22black%22%20stroke-width%3D%223%22%20fill%3D%22none%22%20d%3D%22M55%2068c-17%2C6%20-8%2C23%204%2C28%2012%2C5%2040%2C7%2048%2C-8%209%2C-15%20-9%2C-34%20-26%2C-41%20-17%2C-8%20-45%2C-7%20-62%2C2%20-18%2C8%20-19%2C18%20-20%2C27%20-1%2C9%200%2C29%2027%2C52%2028%2C23%2052%2C33%20102%2C33%2049%2C-1%20130%2C-31%20185%2C-50%2056%2C-19%2074%2C-21%2096%2C-23%2022%2C-2%2029%2C-2%2056%2C6%2027%2C8%2043%2C17%2043%2C17%2014%2C6%2016%2C7%2041%2C16%2025%2C9%2069%2C15%20120%2C11%2051%2C-3%20126%2C-22%20181%2C-32%2054%2C-9%20105%2C-20%20148%2C-23%2042%2C-3%2071%2C1%20104%2C6%2034%2C4%2065%2C14%2098%2C22%22%2F%3E%0A%3C%2Fsvg%3E%0A);_x000D_
}
_x000D_
<div class="author_">Lord Byron</div>
_x000D_
Convenient tool for SVG encoding url-encoder
you can use sorted() method if you want it to return the sorted list. It's more convenient.
l1 = []
n = int(input())
for i in range(n):
user = int(input())
l1.append(user)
sorted(l1,reverse=True)
list.sort() method modifies the list in-place and returns None.
if you still want to use sort you can do this.
l1 = []
n = int(input())
for i in range(n):
user = int(input())
l1.append(user)
l1.sort(reverse=True)
print(l1)
If you want to include render prop components:
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
PropTypes.func
])
Made it work successfully using the 2 methods: Stephan202's encapsulation and multiple event listeners. I have 3 search tabs, let's define their input text id's in an Array:
var ids = new Array("searchtab1", "searchtab2", "searchtab3");
When the content of searchtab1 changes, I want to update searchtab2 and searchtab3. Did it this way for encapsulation:
for (var i in ids) {
$("#" + ids[i]).change(function() {
for (var j in ids) {
if (this != ids[j]) {
$("#" + ids[j]).val($(this).val());
}
}
});
}
Multiple event listeners:
for (var i in ids) {
for (var j in ids) {
if (ids[i] != ids[j]) {
$("#" + ids[i]).change(function() {
$("#" + ids[j]).val($(this).val());
});
}
}
}
I like both methods, but the programmer chose encapsulation, however multiple event listeners worked also. We used Chrome to test it.
first find your binaries file where it is saved. get the path in terminal mine is
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin
then find your local user data path, it is in mostly
C:\usr\local\pgsql\data
now all we have to hit following command in the binary terminal path:
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin>pg_ctl -D "C:\usr\local\pgsql\data" start
all done!
autovaccum launcher started! cheers!
update 4.0.0
See Angular docs for more details https://angular.io/guide/router#fetch-data-before-navigating
original
Using a service is the way to go. In route params you should only pass data that you want to be reflected in the browser URL bar.
See also https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
The router shipped with RC.4 re-introduces data
constructor(private route: ActivatedRoute) {}
const routes: RouterConfig = [
{path: '', redirectTo: '/heroes', pathMatch : 'full'},
{path : 'heroes', component : HeroDetailComponent, data : {some_data : 'some value'}}
];
class HeroDetailComponent {
ngOnInit() {
this.sub = this.route
.data
.subscribe(v => console.log(v));
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
See also the Plunker at https://github.com/angular/angular/issues/9757#issuecomment-229847781
Swift 3.0
Create a ViewController with the UITableViewDelegate and UITableViewDataSource protocols. Then create a tableView inside it, declaring its style to be UITableViewStyle.grouped. This will fix the headers.
lazy var tableView: UITableView = {
let view = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.grouped)
view.delegate = self
view.dataSource = self
view.separatorStyle = .none
return view
}()
I was Forming some Programming Logic Used CHAR(34) for Quotes at Excel : A small Part of same I am posting which can be helpfull ,Hopefully
1 Customers
2 Invoices
Formula Used :
=CONCATENATE("listEvents.Add(",D4,",",CHAR(34),E4,CHAR(34),");")
Result :
listEvents.Add(1,"Customers");
listEvents.Add(2,"Invoices");
guys. I had the same problem before when I'm trying import a .aar package into my project, and unfortunately before make the .aar package as a module-dependence of my project, I had two modules (one about ROS-ANDROID-CV-BRIDGE, one is OPENCV-FOR-ANDROID) already. So, I got this error as you guys meet:
Error:Could not find method android() for arguments [org.ros.gradle_plugins.RosAndroidPlugin$_apply_closure2_closure4@7e550e0e] on project ‘:xxx’ of type org.gradle.api.Project.
So, it's the painful gradle-structure caused this problem when you have several modules in your project, and worse, they're imported in different way or have different types (.jar/.aar packages or just a project of Java library). And it's really a headache matter to make the configuration like compile-version, library dependencies etc. in each subproject compatible with the main-project.
I solved my problem just follow this steps:
? Copy .aar package in app/libs.
? Add this in app/build.gradle file:
repositories {
flatDir {
dirs 'libs' //this way we can find the .aar file in libs folder
}
}
? Add this in your add build.gradle file of the module which you want to apply the .aar dependence (in my situation, just add this in my app/build.gradle file):
dependencies {
compile(name:'package_name', ext:'aar')
}
So, if it's possible, just try export your module-dependence as a .aar package, and then follow this way import it to your main-project. Anyway, I hope this can be a good suggestion and would solve your problem if you have the same situation with me.
.cpp
files are not included (using #include
) into other files. Therefore they don't need include guarding. Main.cpp
will know the names and signatures of the class that you have implemented in class.cpp
only because you have specified all that in class.h
- this is the purpose of a header file. (It is up to you to make sure that class.h
accurately describes the code you implement in class.cpp
.) The executable code in class.cpp
will be made available to the executable code in main.cpp
thanks to the efforts of the linker.
You have to set setOnItemLongClickListener() in the ListView:
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// TODO Auto-generated method stub
Log.v("long clicked","pos: " + pos);
return true;
}
});
The XML for each item in the list (should you use a custom XML) must have android:longClickable="true"
as well (or you can use the convenience method lv.setLongClickable(true);
). This way you can have a list with only some items responding to longclick.
Hope this will help you.
subdate(now(),1) will return yesterdays timestamp The below code will select all rows with yesterday's timestamp
Select * FROM `login` WHERE `dattime` <= subdate(now(),1) AND `dattime` > subdate(now(),2)
If you just want to compare only one row with $lactureName then use following
function checkLectureStatus($lectureName)
{
$con = connectvar();
mysql_select_db("mydatabase", $con);
$result = mysql_query("SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName'");
if(mysql_num_rows($result) > 0)
{
mysql_close($con);
return "Assigned";
}
else
{
mysql_close($con);
return "Available";
}
}
Here is the other way to get scroll position
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
You can just put:
header("HTTP/1.0 500 Internal Server Error");
inside your conditions like:
if (that happened) {
header("HTTP/1.0 500 Internal Server Error");
}
As for the database query, you can just do that like this:
$result = mysql_query("..query string..") or header("HTTP/1.0 500 Internal Server Error");
You should remember that you have to put this code before any html tag (or output).
The Problem is with your code formatting,
inorder to use strtotime()
You should replace '06/Oct/2011:19:00:02'
with 06/10/2011 19:00:02
and date('d/M/Y:H:i:s', $date);
with date('d/M/Y H:i:s', $date);
. Note the spaces in between.
So the final code looks like this
$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);
Use:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) {
writer.write("text to write");
}
catch (IOException ex) {
// Handle me
}
Using try()
will close stream automatically. This version is short, fast (buffered) and enables choosing encoding.
This feature was introduced in Java 7.
In addition to the posts above:
Application.Current.DispatcherUnhandledException
will not catch exceptions that are thrown from a thread other than the main thread. You have to catch those exceptions on the same thread they are thrown. But if you want to Handle them on your global exception handler you can pass it to the main thread:
System.Threading.Thread t = new System.Threading.Thread(() =>
{
try
{
...
//this exception will not be catched by
//Application.DispatcherUnhandledException
throw new Exception("huh..");
...
}
catch (Exception ex)
{
//But we can handle it in the throwing thread
//and pass it to the main thread wehre Application.
//DispatcherUnhandledException can handle it
System.Windows.Application.Current.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action<Exception>((exc) =>
{
throw new Exception("Exception from another Thread", exc);
}), ex);
}
});
Watcher with the deep option didn't work for me.
Instead, I use updated() lifecycle hook which gets executed everytime the component's data changes. Just use it like you do with mounted().
mounted() {
/* to be executed when mounted */
},
updated() {
console.log(this.$route)
}
For your reference, visit the documentation.
Though the question is for button
, but if anyone wants to refresh the page using <a>
, you can simply do
<a href="./">Reload</a>
Perhaps the error message is somewhat misleading, but the gist is that X_train
is a list, not a numpy array. You cannot use array indexing on it. Make it an array first:
out_images = np.array(X_train)[indices.astype(int)]
I had to do the following (in Kubuntu 16.04.3):
sudo apt-get install libaio1 libaio-dev
sudo find / -iname 'libaio.a' -type f
--> resulted in /usr/lib/x86_64-linux-gnu/libaio.a
export LD_LIBRARY_PATH="/usr/lib/oracle/12.2/client64/lib:/usr/lib/x86_64-linux-gnu"
for using git you have to be
root
if not then use sudo
for removing origin :
git remote remove origin
for adding origin :
git remote add origin http://giturl
You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:
body{
min-width:1000px; /* Suppose you want minimum width of 1000px */
width: auto !important; /* Firefox will set width as auto */
width:1000px; /* As IE6 ignores !important it will set width as 1000px; */
}
Or:
body{
min-width:1000px; // Suppose you want minimum width of 1000px
_width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}
I use MinGW tool set which provides mingw32-make
build tool, if you have it in your PATH
system variables, in Windows Command Prompt just go into the directory containing the files and type this command:
mingw32-make -f Makefile.win
and it's done.
Try this:
data=pd.read_csv('C:\Users\Desktop\Data Exploration.csv')
data.head(5)
first=data['1st Gift']
last=data['Last Gift']
maxi=data['Largest Gift']
l_1=np.mean(first)-3*np.std(first)
u_1=np.mean(first)+3*np.std(first)
m=np.abs(data['1st Gift']-np.mean(data['1st Gift']))>3*np.std(data['1st Gift'])
pd.value_counts(m)
l=first[m]
data.loc[:,'1st Gift'][m==True]=np.mean(data['1st Gift'])+3*np.std(data['1st Gift'])
data['1st Gift'].head()
m=np.abs(data['Last Gift']-np.mean(data['Last Gift']))>3*np.std(data['Last Gift'])
pd.value_counts(m)
l=last[m]
data.loc[:,'Last Gift'][m==True]=np.mean(data['Last Gift'])+3*np.std(data['Last Gift'])
data['Last Gift'].head()
I wanted to be able to access my application with the HTML5 mode and a fixed token and then switch to the hashbang method (to keep the token so the user can refresh his page).
URL for accessing my app:
http://myapp.com/amazing_url?token=super_token
Then when the user loads the page:
http://myapp.com/amazing_url?token=super_token#/amazing_url
Then when the user navigates:
http://myapp.com/amazing_url?token=super_token#/another_url
With this I keep the token in the URL and keep the state when the user is browsing. I lost a bit of visibility of the URL, but there is no perfect way of doing it.
So don't enable the HTML5 mode and then add this controller:
.config ($stateProvider)->
$stateProvider.state('home-loading', {
url: '/',
controller: 'homeController'
})
.controller 'homeController', ($state, $location)->
if window.location.pathname != '/'
$location.url(window.location.pathname+window.location.search).replace()
else
$state.go('home', {}, { location: 'replace' })
after trying to fix a similar problem my self, where I had changed from @PrimaryKey(autoGenerate = true)
to int UUID
, I couldn't find how to write my migration so I changed the table name, it's an easy fix, and ok if you working with a personal/small app
I want to mention the Ning Async Http Client Library. I've never used it but my colleague raves about it as compared to the Apache Http Client, which I've always used in the past. I was particularly interested to learn it is based on Netty, the high-performance asynchronous i/o framework, with which I am more familiar and hold in high esteem.
Just try this line:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
after:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
This may not be as slick as a one-liner, but I use it to perform date manipulation mainly for reports:
DECLARE @Date datetime
SET @Date = GETDATE()
-- Set all time components to zero
SET @Date = DATEADD(ms, -DATEPART(ms, @Date), @Date) -- milliseconds = 0
SET @Date = DATEADD(ss, -DATEPART(ss, @Date), @Date) -- seconds = 0
SET @Date = DATEADD(mi, -DATEPART(mi, @Date), @Date) -- minutes = 0
SET @Date = DATEADD(hh, -DATEPART(hh, @Date), @Date) -- hours = 0
-- Extra manipulation for month and year
SET @Date = DATEADD(dd, -DATEPART(dd, @Date) + 1, @Date) -- day = 1
SET @Date = DATEADD(mm, -DATEPART(mm, @Date) + 1, @Date) -- month = 1
I use this to get hourly, daily, monthly, and yearly dates used for reporting and performance indicators, etc.
I have created a method that helps with getting the stackTrace:
private static String getStackTrace(Exception ex) {
StringBuffer sb = new StringBuffer(500);
StackTraceElement[] st = ex.getStackTrace();
sb.append(ex.getClass().getName() + ": " + ex.getMessage() + "\n");
for (int i = 0; i < st.length; i++) {
sb.append("\t at " + st[i].toString() + "\n");
}
return sb.toString();
}
Before increasing the max_connections variable, you have to check how many non-interactive connection you have by running show processlist command.
If you have many sleep connection, you have to decrease the value of the "wait_timeout" variable to close non-interactive connection after waiting some times.
SHOW SESSION VARIABLES LIKE 'wait_timeout';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout | 28800 |
+---------------+-------+
the value is in second, it means that non-interactive connection still up to 8 hours.
SET session wait_timeout=600; Query OK, 0 rows affected (0.00 sec)
After 10 minutes if the sleep connection still sleeping the mysql or MariaDB drop that connection.
You could just use the imageView's image cache. It will render the entire view as it is layed out (scaled,bordered with a background etc) to a new bitmap.
just make sure it built.
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
there's your bitmap as the screen saw it.
To create a view controller:
UIViewController * vc = [[UIViewController alloc] init];
To call a view controller (must be called from within another viewcontroller):
[self presentViewController:vc animated:YES completion:nil];
For one, use nil rather than null.
Loading a view controller from the storyboard:
NSString * storyboardName = @"MainStoryboard";
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"IDENTIFIER_OF_YOUR_VIEWCONTROLLER"];
[self presentViewController:vc animated:YES completion:nil];
Identifier
of your view controller is either equal to the class name of your view controller, or a Storyboard ID that you can assign in the identity inspector of your storyboard.
run:
vagrant ssh-config > .ssh.config
and then in config/deploy.rb
role :web, "default"
role :app, "default"
set :use_sudo, true
set :user, 'root'
set :run_method, :sudo
# Must be set for the password prompt from git to work
default_run_options[:pty] = true
ssh_options[:forward_agent] = true
ssh_options[:config] = '.ssh.config'
In Webdriver, you should use driver.switchTo().defaultContent();
to get out of a frame.
You need to get out of all the frames first, then switch into outer frame again.
// between step 4 and step 5
// remove selenium.selectFrame("relative=up");
driver.switchTo().defaultContent(); // you are now outside both frames
driver.switchTo().frame("cq-cf-frame");
// now continue step 6
driver.findElement(By.xpath("//button[text()='OK']")).click();
@JoshAdel covered a lot of it, but if you just want to time the execution of an entire script, you can run it under time
on a unix-like system.
kotai:~ chmullig$ cat sleep.py
import time
print "presleep"
time.sleep(10)
print "post sleep"
kotai:~ chmullig$ python sleep.py
presleep
post sleep
kotai:~ chmullig$ time python sleep.py
presleep
post sleep
real 0m10.035s
user 0m0.017s
sys 0m0.016s
kotai:~ chmullig$
First, convert the timestamp using the built-in eloquent functionality, as described in this answer.
Then you can just use Carbon's min()
or max()
function for comparison. For example:
$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0);
$dt2 = Carbon::create(2014, 1, 30, 0, 0, 0);
echo $dt1->min($dt2);
This will echo
the lesser of the two dates, which in this case is $dt1
.
Check Screen Options (dropdown tab in the upper right hand corner of the page), and make sure there are sane settings for what to show on screen. All the column settings should be checked, and there should be a positive number of media items being shown on screen.
If that is ok, then check Settings ? Media and make sure that Uploading Files folder is set to wp-content/uploads
.
I believe these are the only settings that can be changed from the administrative screens.
request.remote_ip
is an interpretation of all the available IP address information and it will make a best-guess. If you access the variables directly you assume responsibility for testing them in the correct precedence order. Proxies introduce a number of headers that create environment variables with different names.
for
or break
.The only case when both do (nearly) the same thing is in the main()
function, as a return from main performs an exit()
.
In most C implementations, main
is a real function called by some startup code that does something like int ret = main(argc, argv); exit(ret);
. The C standard guarantees that something equivalent to this happens if main
returns, however the implementation handles it.
Example with return
:
#include <stdio.h>
void f(){
printf("Executing f\n");
return;
}
int main(){
f();
printf("Back from f\n");
}
If you execute this program it prints:
Executing f Back from f
Another example for exit()
:
#include <stdio.h>
#include <stdlib.h>
void f(){
printf("Executing f\n");
exit(0);
}
int main(){
f();
printf("Back from f\n");
}
If you execute this program it prints:
Executing f
You never get "Back from f". Also notice the #include <stdlib.h>
necessary to call the library function exit()
.
Also notice that the parameter of exit()
is an integer (it's the return status of the process that the launcher process can get; the conventional usage is 0 for success or any other value for an error).
The parameter of the return statement is whatever the return type of the function is. If the function returns void, you can omit the return at the end of the function.
Last point, exit()
come in two flavors _exit()
and exit()
. The difference between the forms is that exit()
(and return from main) calls functions registered using atexit()
or on_exit()
before really terminating the process while _exit()
(from #include <unistd.h>
, or its synonymous _Exit from #include <stdlib.h>
) terminates the process immediately.
Now there are also issues that are specific to C++.
C++ performs much more work than C when it is exiting from functions (return
-ing). Specifically it calls destructors of local objects going out of scope. In most cases programmers won't care much of the state of a program after the processus stopped, hence it wouldn't make much difference: allocated memory will be freed, file ressource closed and so on. But it may matter if your destructor performs IOs. For instance automatic C++ OStream
locally created won't be flushed on a call to exit and you may lose some unflushed data (on the other hand static OStream
will be flushed).
This won't happen if you are using the good old C FILE*
streams. These will be flushed on exit()
. Actually, the rule is the same that for registered exit functions, FILE*
will be flushed on all normal terminations, which includes exit()
, but not calls to _exit()
or abort().
You should also keep in mind that C++ provide a third way to get out of a function: throwing an exception. This way of going out of a function will call destructor. If it is not catched anywhere in the chain of callers, the exception can go up to the main() function and terminate the process.
Destructors of static C++ objects (globals) will be called if you call either return
from main()
or exit()
anywhere in your program. They wont be called if the program is terminated using _exit()
or abort()
. abort()
is mostly useful in debug mode with the purpose to immediately stop the program and get a stack trace (for post mortem analysis). It is usually hidden behind the assert()
macro only active in debug mode.
When is exit() useful ?
exit()
means you want to immediately stops the current process. It can be of some use for error management when we encounter some kind of irrecoverable issue that won't allow for your code to do anything useful anymore. It is often handy when the control flow is complicated and error codes has to be propagated all way up. But be aware that this is bad coding practice. Silently ending the process is in most case the worse behavior and actual error management should be preferred (or in C++ using exceptions).
Direct calls to exit()
are especially bad if done in libraries as it will doom the library user and it should be a library user's choice to implement some kind of error recovery or not. If you want an example of why calling exit()
from a library is bad, it leads for instance people to ask this question.
There is an undisputed legitimate use of exit()
as the way to end a child process started by fork() on Operating Systems supporting it. Going back to the code before fork() is usually a bad idea. This is the rationale explaining why functions of the exec() family will never return to the caller.