First of all, run your IDE as Admin. After that, right click the project folder -> Project Facets and make sure that the Java Version is set correct. On my PC. (For Example 1.8) Now it should work.
Don't just start your server, for example Wildfly, using the cmd. It has to be launched within the IDE and now visit your localhost URL. Example: http://localhost:8080/HelloWorldServlet/HelloWorld
Example using std::vector
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
int main()
{
/// Initilaize vector using intitializer list ( requires C++11 )
std::vector<std::string> names = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
// Sort names using std::sort
std::sort(names.begin(), names.end() );
// Print using range-based and const auto& for ( both requires C++11 )
for(const auto& currentName : names)
{
std::cout << currentName << std::endl;
}
//... or by using your orignal for loop ( vector support [] the same way as plain arrays )
for(int y = 0; y < names.size(); y++)
{
std:: cout << names[y] << std::endl; // you were outputting name[z], but only increasing y, thereby only outputting element z ( 14 )
}
return 0;
}
This completely avoids using plain arrays, and lets you use the std::sort function. You might need to update you compiler to use the = {...}
You can instead add them by using vector.push_back("name")
Video file example (HTML + Javascript):
function upload_check()
{
var upl = document.getElementById("file_id");
var max = document.getElementById("max_id").value;
if(upl.files[0].size > max)
{
alert("File too big!");
upl.value = "";
}
};
_x000D_
<form action="some_script" method="post" enctype="multipart/form-data">
<input id="max_id" type="hidden" name="MAX_FILE_SIZE" value="250000000" />
<input onchange="upload_check()" id="file_id" type="file" name="file_name" accept="video/*" />
<input type="submit" value="Upload"/>
</form>
_x000D_
adding log4j-1.2.12.jar file has resolved the issue for me
HTML
<div>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>
</div>
<a id="more" href="#">Read more </a>
<a id="less" href="#">Read less </a>
CSS
<style type="text/css">
div{
width:100px;
height:50px;
display:block;
border:1px solid red;
padding:10px;
overflow:hidden;
}
</style>
jQuery
<link rel="stylesheet"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/start/jquery-ui.css"
type="text/css" media="all" />
<script type="text/javascript">
var h = $('div')[0].scrollHeight;
$('#more').click(function(e) {
e.stopPropagation();
$('div').animate({
'height': h
})
$('#more').hide();
$('#less').show();
});
$('#less').click(function(e) {
$('#more').show();
$('#less').hide();
});
$(document).click(function() {
$('div').animate({
'height': '50px'
})
})
$(document).ready(function(){
$('#less').hide();
})
</script>
I solved the simmilar problem, when i tried to push to repo via gitlab ci/cd pipeline by the command "gem install rake && bundle install"
Step1:
npm install bootstrap@latest --save-dev
This will install the latest version of the bootstrap,
However, the specified version can be installed by adding the version number
Step2: Open styles.css and add the following
@import "~bootstrap/dist/css/bootstrap.css"
The general idea behind creating "optional arguments" is to first define an intermediate command that scans ahead to detect what characters are coming up next in the token stream and then inserts the relevant macros to process the argument(s) coming up as appropriate. This can be quite tedious (although not difficult) using generic TeX programming. LaTeX's \@ifnextchar
is quite useful for such things.
The best answer for your question is to use the new xparse
package. It is part of the LaTeX3 programming suite and contains extensive features for defining commands with quite arbitrary optional arguments.
In your example you have a \sec
macro that either takes one or two braced arguments. This would be implemented using xparse
with the following:
\documentclass{article} \usepackage{xparse} \begin{document} \DeclareDocumentCommand\sec{ m g }{% {#1% \IfNoValueF {#2} { and #2}% }% } (\sec{Hello}) (\sec{Hello}{Hi}) \end{document}
The argument { m g }
defines the arguments of \sec
; m
means "mandatory argument" and g
is "optional braced argument". \IfNoValue(T)(F)
can then be used to check whether the second argument was indeed present or not. See the documentation for the other types of optional arguments that are allowed.
A postback is the process of re-loading a page, so if you want the page to close after the postback then you need to set your window.close() javascript to run with the browser's onload event during that postback, normally done using the ClientScript.RegisterStartupScript()
function.
But are you sure this is what you want to do? Closing pages tends to piss off users.
After trying some things the only thing that worked for me is:
conda install -c anaconda py-xgboost
HTTPS using Jersey client has two different version if you are using java 6 ,7 and 8 then
SSLContext sc = SSLContext.getInstance("SSL");
If using java 8 then
SSLContext sc = SSLContext.getInstance("TLSv1");
System.setProperty("https.protocols", "TLSv1");
Please find working code
POM
<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>WebserviceJersey2Spring</groupId>
<artifactId>WebserviceJersey2Spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<jersey.version>2.16</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Jersey -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
</dependency>
<!-- Jersey + Spring -->
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-context</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-beans</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-core</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-web</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>jersey-server</artifactId>
<groupId>org.glassfish.jersey.core</groupId>
</exclusion>
<exclusion>
<artifactId>
jersey-container-servlet-core
</artifactId>
<groupId>org.glassfish.jersey.containers</groupId>
</exclusion>
<exclusion>
<artifactId>hk2</artifactId>
<groupId>org.glassfish.hk2</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
JAVA CLASS
package com.example.client;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.springframework.http.HttpStatus;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
public class JerseyClientGet {
public static void main(String[] args) {
String username = "username";
String password = "p@ssword";
String input = "{\"userId\":\"12345\",\"name \":\"Viquar\",\"surname\":\"Khan\",\"Email\":\"[email protected]\"}";
try {
//SSLContext sc = SSLContext.getInstance("SSL");//Java 6
SSLContext sc = SSLContext.getInstance("TLSv1");//Java 8
System.setProperty("https.protocols", "TLSv1");//Java 8
TrustManager[] trustAllCerts = { new InsecureTrustManager() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
Client client = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
HttpAuthenticationFeature feature = HttpAuthenticationFeature.universalBuilder()
.credentialsForBasic(username, password).credentials(username, password).build();
client.register(feature);
//PUT request, if need uncomment it
//final Response response = client
//.target("https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations")
//.request().put(Entity.entity(input, MediaType.APPLICATION_JSON), Response.class);
//GET Request
final Response response = client
.target("https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations")
.request().get();
if (response.getStatus() != HttpStatus.OK.value()) { throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus()); }
String output = response.readEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
HELPER CLASS
package com.example.client;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class InsecureHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
Helper class
package com.example.client;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class InsecureTrustManager implements X509TrustManager {
/**
* {@inheritDoc}
*/
@Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
// Everyone is trusted!
}
/**
* {@inheritDoc}
*/
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
// Everyone is trusted!
}
/**
* {@inheritDoc}
*/
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
Once you start running application will get Certificate error ,download certificate from browser and add into
C:\java-8\jdk1_8_0\jre\lib\security
Add into cacerts , you will get details in following links.
Few useful link to understand error
http://www.9threes.com/2015/01/restful-java-client-with-jersey-client.html
http://magicmonster.com/kb/prg/java/ssl/pkix_path_building_failed.html
I have tested following code for get and post method with SSL and basic Authentication here you can skip SSL Certificate , you can directly copy three class and add jar into java project and run.
package com.rest.client;
import java.io.IOException;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.glassfish.jersey.filter.LoggingFilter;
import com.rest.dto.EarUnearmarkCollateralInput;
public class RestClientTest {
/**
* @param args
*/
public static void main(String[] args) {
try {
//
sslRestClientGETReport();
//
sslRestClientPostEarmark();
//
sslRestClientGETRankColl();
//
} catch (KeyManagementException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
//
private static WebTarget target = null;
private static String userName = "username";
private static String passWord = "password";
//
public static void sslRestClientGETReport() throws KeyManagementException, IOException, NoSuchAlgorithmException {
//
//
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager[] trustAllCerts = { new InsecureTrustManager() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
//
Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
//
String baseUrl = "https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations/report";
c.register(HttpAuthenticationFeature.basic(userName, passWord));
target = c.target(baseUrl);
target.register(new LoggingFilter());
String responseMsg = target.request().get(String.class);
System.out.println("-------------------------------------------------------");
System.out.println(responseMsg);
System.out.println("-------------------------------------------------------");
//
}
public static void sslRestClientGET() throws KeyManagementException, IOException, NoSuchAlgorithmException {
//Query param Search={JSON}
//
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager[] trustAllCerts = { new InsecureTrustManager() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
//
Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
//
String baseUrl = "https://localhost:7002/VaquarKhanWeb";
//
c.register(HttpAuthenticationFeature.basic(userName, passWord));
target = c.target(baseUrl);
target = target.path("employee/api/v1/informations/employee/data").queryParam("search","%7B\"name\":\"vaquar\",\"surname\":\"khan\",\"age\":\"30\",\"type\":\"admin\""%7D");
target.register(new LoggingFilter());
String responseMsg = target.request().get(String.class);
System.out.println("-------------------------------------------------------");
System.out.println(responseMsg);
System.out.println("-------------------------------------------------------");
//
}
//TOD need to fix
public static void sslRestClientPost() throws KeyManagementException, IOException, NoSuchAlgorithmException {
//
//
Employee employee = new Employee("vaquar", "khan", "30", "E");
//
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager[] trustAllCerts = { new InsecureTrustManager() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
//
Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
//
String baseUrl = "https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations/employee";
c.register(HttpAuthenticationFeature.basic(userName, passWord));
target = c.target(baseUrl);
target.register(new LoggingFilter());
//
Response response = target.request().put(Entity.json(employee));
String output = response.readEntity(String.class);
//
System.out.println("-------------------------------------------------------");
System.out.println(output);
System.out.println("-------------------------------------------------------");
}
}
Jars
repository/javax/ws/rs/javax.ws.rs-api/2.0/javax.ws.rs-api-2.0.jar"
repository/org/glassfish/jersey/core/jersey-client/2.6/jersey-client-2.6.jar"
repository/org/glassfish/jersey/core/jersey-common/2.6/jersey-common-2.6.jar"
repository/org/glassfish/hk2/hk2-api/2.2.0/hk2-api-2.2.0.jar"
repository/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.6/jersey-guava-2.6.jar"
repository/org/glassfish/hk2/hk2-locator/2.2.0/hk2-locator-2.2.0.jar"
repository/org/glassfish/hk2/hk2-utils/2.2.0/hk2-utils-2.2.0.jar"
repository/org/javassist/javassist/3.15.0-GA/javassist-3.15.0-GA.jar"
repository/org/glassfish/hk2/external/javax.inject/2.2.0/javax.inject-2.2.0.jar"
repository/javax/annotation/javax.annotation-api/1.2/javax.annotation-api-1.2.jar"
genson-1.3.jar"
From the main Form, you have to:
Additionally,I have found this on google and I wanted to share this to those who are still searching for answers. (for global)
I think you have to be using user32.dll
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x0312)
{
/* Note that the three lines below are not needed if you only want to register one hotkey.
* The below lines are useful in case you want to register multiple keys, which you can use a switch with the id as argument, or if you want to know which key/modifier was pressed for some particular reason. */
Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); // The key of the hotkey that was pressed.
KeyModifier modifier = (KeyModifier)((int)m.LParam & 0xFFFF); // The modifier of the hotkey that was pressed.
int id = m.WParam.ToInt32(); // The id of the hotkey that was pressed.
MessageBox.Show("Hotkey has been pressed!");
// do something
}
}
Further read this http://www.fluxbytes.com/csharp/how-to-register-a-global-hotkey-for-your-application-in-c/
On Telegram Desktop for macOS, the shortcuts differ. You can right-click a highlighted text, then hover over Transformations
to see the available options:
var currentTallest = 0,_x000D_
currentRowStart = 0,_x000D_
rowDivs = new Array(),_x000D_
$el,_x000D_
topPosition = 0;_x000D_
_x000D_
$('.blocks').each(function() {_x000D_
_x000D_
$el = $(this);_x000D_
topPostion = $el.position().top;_x000D_
_x000D_
if (currentRowStart != topPostion) {_x000D_
_x000D_
// we just came to a new row. Set all the heights on the completed row_x000D_
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {_x000D_
rowDivs[currentDiv].height(currentTallest);_x000D_
}_x000D_
_x000D_
// set the variables for the new row_x000D_
rowDivs.length = 0; // empty the array_x000D_
currentRowStart = topPostion;_x000D_
currentTallest = $el.height();_x000D_
rowDivs.push($el);_x000D_
_x000D_
} else {_x000D_
_x000D_
// another div on the current row. Add it to the list and check if it's taller_x000D_
rowDivs.push($el);_x000D_
currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);_x000D_
_x000D_
}_x000D_
_x000D_
// do the last row_x000D_
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {_x000D_
rowDivs[currentDiv].height(currentTallest);_x000D_
}_x000D_
_x000D_
});?
_x000D_
$('.blocks') would be changed to use whatever CSS selector you need to equalize.
_x000D_
Dear You have used two Intent launcher in your Manifest. Make only one Activity as launcher: Your manifest activity is :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.th.mybook"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainTabPanel"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="MyBookActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.ALTERNATIVE" />
</intent-filter>
</activity>
</application>
</manifest>
now write code will be ( i have made your 'MyActivityBook' your default activity launcher. Copy and paste it on your manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.th.mybook"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainTabPanel"
android:label="@string/app_name" >
</activity>
<activity
android:name="MyBookActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and Second error may be if you copy paste old code then please update com.example.packagename.FILE_NAME
hope this will work !
use
path_to_exe >> log_file
to see the output of your command also errors can be redirected with
path_to_exe &> log_file
also you can use
crontab -l
to check if your edits were saved.
If you are doing a loading screen, just set the parameter to not keep it in activity stack. In your manifest.xml, where you define your activity do:
<activity android:name=".LoadingScreen" android:noHistory="true" ... />
And in your code there is no need to call .finish() anymore. Just do startActivity(i);
There is also no need to keep a instance of your current activity in a separate field. You can always access it like LoadingScreen.this.doSomething()
instead of private LoadingScreen loadingScreen;
Use this:
$stmt = $user->runQuery("SELECT * FROM tbl WHERE ID=:id");
$stmt->bindparam(":id",$id);
$stmt->execute();
$stmt->bindColumn("a_b",$xx);
$stmt->bindColumn("c_d",$yy);
while($rows = $stmt->fetch(PDO::FETCH_BOUND))
{
//---insert into new tble
}
You cannot open in a new tab programmatically, it's a browser functionality. You can open a link in an external window . Have a look here
The other answers are fine, but this is a little cleaner, in that it only gives the values like you would get from a DISTINCT query, without any cruft from Django.
>>> set(ProductOrder.objects.values_list('category', flat=True))
{u'category1', u'category2', u'category3', u'category4'}
or
>>> list(set(ProductOrder.objects.values_list('category', flat=True)))
[u'category1', u'category2', u'category3', u'category4']
And, it works without PostgreSQL.
This is less efficient than using a .distinct(), presuming that DISTINCT in your database is faster than a python set
, but it's great for noodling around the shell.
Try this:
b = [ entry.split(',') for entry in a ]
b = [ b[i] if i % 3 == 0 else int(b[i]) for i in xrange(0, len(b)) ]
You can set the hours, minutes, seconds and microseconds to whatever you like
datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
but trutheality's answer is probably best when they are all to be zero and you can just compare the .date()
s of the times
Maybe it is faster though if you have to compare hundreds of datetimes because you only need to do the replace()
once vs hundreds of calls to date()
I use rake db:reset
which drops and then recreates the database and includes your seeds.rb file.
http://guides.rubyonrails.org/migrations.html#resetting-the-database
Put this right before the closing Body tag at the bottom of the page.
<script>
if (location.hash) {
location.href = location.hash;
}
</script>
jQuery is actually not required.
In the app on android I opened Menu (Command + M in Genymotion) -> Dev Settings -> Debug server host & port for device
set the value to: localhost:8081
It worked for me.
Try this DEMO:
$(document).ready(function () {
$("input[name='vehicle']").change(function () {
var maxAllowed = 3;
var cnt = $("input[name='vehicle']:checked").length;
if (cnt > maxAllowed)
{
$(this).prop("checked", "");
alert('Select maximum ' + maxAllowed + ' Levels!');
}
});
});
You need to handle two scenarios:
If you just need a base class you can use, here's a Swift 3 version:
import UIKit
final class SwipeNavigationController: UINavigationController {
// MARK: - Lifecycle
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
delegate = self
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
delegate = self
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
// This needs to be in here, not in init
interactivePopGestureRecognizer?.delegate = self
}
deinit {
delegate = nil
interactivePopGestureRecognizer?.delegate = nil
}
// MARK: - Overrides
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
duringPushAnimation = true
super.pushViewController(viewController, animated: animated)
}
// MARK: - Private Properties
fileprivate var duringPushAnimation = false
}
// MARK: - UINavigationControllerDelegate
extension SwipeNavigationController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
guard let swipeNavigationController = navigationController as? SwipeNavigationController else { return }
swipeNavigationController.duringPushAnimation = false
}
}
// MARK: - UIGestureRecognizerDelegate
extension SwipeNavigationController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard gestureRecognizer == interactivePopGestureRecognizer else {
return true // default value
}
// Disable pop gesture in two situations:
// 1) when the pop animation is in progress
// 2) when user swipes quickly a couple of times and animations don't have time to be performed
return viewControllers.count > 1 && duringPushAnimation == false
}
}
If you end up needing to act as a UINavigationControllerDelegate
in another class, you can write a delegate forwarder similar to this answer.
Adapted from source in Objective-C: https://github.com/fastred/AHKNavigationController
I have netbeans 6.9.1 open right now and ALT+SHIFT+F indents only the lines you have selected.
If no lines are selected then it will indent the whole document you are in.
1 possibly unintended behavior is that if you have selected ONLY 1 line, it must be selected completely, otherwise it does nothing. But you don't have to completely select the last line of a group nor the first.
I expected it to indent only one line by just selecting the first couple of chars but didn't work, yea i know i am lazy as hell...
try below code hope use full for you:-
CityAsyncTask cst = new CityAsyncTask(HomeScreenUserLocation.this,
latitude, longitude);
cst.execute();
String lo = null;
try {
lo = cst.get().toString();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and AsyncTask
public class CityAsyncTask extends AsyncTask<String, String, String> {
Activity act;
double latitude;
double longitude;
public CityAsyncTask(Activity act, double latitude, double longitude) {
// TODO Auto-generated constructor stub
this.act = act;
this.latitude = latitude;
this.longitude = longitude;
}
@Override
protected String doInBackground(String... params) {
String result = "";
Geocoder geocoder = new Geocoder(act, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
Log.e("Addresses", "-->" + addresses);
result = addresses.get(0).toString();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.
<div id='myframe'>
<?php
/*
Use below function to display final HTML inside this div
*/
//Display Frame
echo displayFrame();
?>
</div>
<?php
/*
Function to display frame from another domain
*/
function displayFrame()
{
$webUrl = 'http://[external-web-domain.com]/';
//Get HTML from the URL
$content = file_get_contents($webUrl);
//Add custom JS to returned HTML content
$customJS = "
<script>
/* Here I am writing a sample jQuery to hide the navigation menu
You can write your own jQuery for this content
*/
//Hide Navigation bar
jQuery(\".navbar\").hide();
</script>";
//Append Custom JS with HTML
$html = $content . $customJS;
//Return customized HTML
return $html;
}
I think Octave only return one value which is the first return value, in your case, 'array'.
And Octave print it as "ans".
Others, 'listp','freep' were not printed.
Because it showed up within the function.
Try this out:
[ A, B, C] = initialize( 4 )
And the 'array','listp','freep' will print as A, B and C.
If you'd like to initialize the array to values other than 0, with gcc
you can do:
int array[1024] = { [ 0 ... 1023 ] = -1 };
This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99
to compile your code.
<i class="fa" v-bind:class="cravings"></i>
and add in computed :
computed: {
cravings: function() {
return this.content['cravings'] ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline';
}
}
If you are using LINUX, you can use pyALSAAUDIO. For windows, we have PyAudio and there is also a library called SoundAnalyse.
I found an example for Linux here:
#!/usr/bin/python
## This is an example of a simple sound capture script.
##
## The script opens an ALSA pcm for sound capture. Set
## various attributes of the capture, and reads in a loop,
## Then prints the volume.
##
## To test it out, run it and shout at your microphone:
import alsaaudio, time, audioop
# Open the device in nonblocking capture mode. The last argument could
# just as well have been zero for blocking mode. Then we could have
# left out the sleep call in the bottom of the loop
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)
# Set attributes: Mono, 8000 Hz, 16 bit little endian samples
inp.setchannels(1)
inp.setrate(8000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
# The period size controls the internal number of frames per period.
# The significance of this parameter is documented in the ALSA api.
# For our purposes, it is suficcient to know that reads from the device
# will return this many frames. Each frame being 2 bytes long.
# This means that the reads below will return either 320 bytes of data
# or 0 bytes of data. The latter is possible because we are in nonblocking
# mode.
inp.setperiodsize(160)
while True:
# Read data from device
l,data = inp.read()
if l:
# Return the maximum of the absolute value of all samples in a fragment.
print audioop.max(data, 2)
time.sleep(.001)
Why Is There No Floating Point Range Implementation In The Standard Library?
As made clear by all the posts here, there is no floating point version of range()
. That said, the omission makes sense if we consider that the range()
function is often used as an index (and of course, that means an accessor) generator. So, when we call range(0,40)
, we're in effect saying we want 40 values starting at 0, up to 40, but non-inclusive of 40 itself.
When we consider that index generation is as much about the number of indices as it is their values, the use of a float implementation of range()
in the standard library makes less sense. For example, if we called the function frange(0, 10, 0.25)
, we would expect both 0 and 10 to be included, but that would yield a generator with 41 values, not the 40 one might expect from 10/0.25
.
Thus, depending on its use, an frange()
function will always exhibit counter intuitive behavior; it either has too many values as perceived from the indexing perspective or is not inclusive of a number that reasonably should be returned from the mathematical perspective. In other words, it's easy to see how such a function would appear to conflate two very different use cases – the naming implies the indexing use case; the behavior implies a mathematical one.
The Mathematical Use Case
With that said, as discussed in other posts, numpy.linspace()
performs the generation from the mathematical perspective nicely:
numpy.linspace(0, 10, 41)
array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75,
2. , 2.25, 2.5 , 2.75, 3. , 3.25, 3.5 , 3.75,
4. , 4.25, 4.5 , 4.75, 5. , 5.25, 5.5 , 5.75,
6. , 6.25, 6.5 , 6.75, 7. , 7.25, 7.5 , 7.75,
8. , 8.25, 8.5 , 8.75, 9. , 9.25, 9.5 , 9.75, 10.
])
The Indexing Use Case
And for the indexing perspective, I've written a slightly different approach with some tricksy string magic that allows us to specify the number of decimal places.
# Float range function - string formatting method
def frange_S (start, stop, skip = 1.0, decimals = 2):
for i in range(int(start / skip), int(stop / skip)):
yield float(("%0." + str(decimals) + "f") % (i * skip))
Similarly, we can also use the built-in round
function and specify the number of decimals:
# Float range function - rounding method
def frange_R (start, stop, skip = 1.0, decimals = 2):
for i in range(int(start / skip), int(stop / skip)):
yield round(i * skip, ndigits = decimals)
A Quick Comparison & Performance
Of course, given the above discussion, these functions have a fairly limited use case. Nonetheless, here's a quick comparison:
def compare_methods (start, stop, skip):
string_test = frange_S(start, stop, skip)
round_test = frange_R(start, stop, skip)
for s, r in zip(string_test, round_test):
print(s, r)
compare_methods(-2, 10, 1/3)
The results are identical for each:
-2.0 -2.0
-1.67 -1.67
-1.33 -1.33
-1.0 -1.0
-0.67 -0.67
-0.33 -0.33
0.0 0.0
...
8.0 8.0
8.33 8.33
8.67 8.67
9.0 9.0
9.33 9.33
9.67 9.67
And some timings:
>>> import timeit
>>> setup = """
... def frange_s (start, stop, skip = 1.0, decimals = 2):
... for i in range(int(start / skip), int(stop / skip)):
... yield float(("%0." + str(decimals) + "f") % (i * skip))
... def frange_r (start, stop, skip = 1.0, decimals = 2):
... for i in range(int(start / skip), int(stop / skip)):
... yield round(i * skip, ndigits = decimals)
... start, stop, skip = -1, 8, 1/3
... """
>>> min(timeit.Timer('string_test = frange_s(start, stop, skip); [x for x in string_test]', setup=setup).repeat(30, 1000))
0.024284090992296115
>>> min(timeit.Timer('round_test = frange_r(start, stop, skip); [x for x in round_test]', setup=setup).repeat(30, 1000))
0.025324633985292166
Looks like the string formatting method wins by a hair on my system.
The Limitations
And finally, a demonstration of the point from the discussion above and one last limitation:
# "Missing" the last value (10.0)
for x in frange_R(0, 10, 0.25):
print(x)
0.25
0.5
0.75
1.0
...
9.0
9.25
9.5
9.75
Further, when the skip
parameter is not divisible by the stop
value, there can be a yawning gap given the latter issue:
# Clearly we know that 10 - 9.43 is equal to 0.57
for x in frange_R(0, 10, 3/7):
print(x)
0.0
0.43
0.86
1.29
...
8.14
8.57
9.0
9.43
There are ways to address this issue, but at the end of the day, the best approach would probably be to just use Numpy.
Vanilla JavaScript solution:
document.body.innerHTML = document.body.innerHTML.replace(/Original/g, "New")
This is the configuration file for Maven. It can be specified at two levels:
User Level. This settings.xml file provides configuration for a single user, and is normally provided in ${user.home}/.m2/settings.xml.
NOTE: This location can be overridden with the CLI option:
-s /path/to/user/settings.xml
Global Level. This settings.xml file provides configuration for all Maven users on a machine (assuming they're all using the same Maven installation). It's normally provided in ${maven.home}/conf/settings.xml.
NOTE: This location can be overridden with the CLI option:
-gs /path/to/global/settings.xml
Using dt.weekday_name
is deprecated since pandas 0.23.0
, instead, use dt.day_name()
:
df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['my_dates'].dt.day_name()
0 Thursday
1 Friday
2 Saturday
Name: my_dates, dtype: object
First of all, the provided long code:
<xsl:choose>
<xsl:when test="OU_NAME='OU_ADDR1'"> --comparing two elements coming from XML
<!--remove if adrees already contain operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="OU_NAME"/>
<fo:block/>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:otherwise>
</xsl:choose>
is equivalent to this, much shorter code:
<xsl:if test="not(OU_NAME='OU_ADDR1)'">
<xsl:value-of select="OU_NAME"/>
</xsl:if>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
Now, to your question:
how to compare two elements coming from xml as string
In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator =
and the function not()
together with the operator =
.
$str1 = $str2
evaluates to true()
exactly when the string $str1
is equal to the string $str2
.
not($str1 = $str2)
evaluates to true()
exactly when the string $str1
is not equal to the string $str2
.
There is also the !=
operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.
Now, the rules for comparing two element nodes are similar:
$el1 = $el2
evaluates to true()
exactly when the string value of $el1
is equal to the string value of $el2
.
not($el1 = $el2)
evaluates to true()
exactly when the string value of $el1
is not equal to the string value of $el2
.
However, if one of the operands of =
is a node-set, then
$ns = $str
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string $str
$ns1 = $ns2
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string value of some node from $ns2
Therefore, the expression:
OU_NAME='OU_ADDR1'
evaluates to true()
only when there is at least one element child of the current node that is named OU_NAME
and whose string value is the string 'OU_ADDR1'.
This is obviously not what you want!
Most probably you want:
OU_NAME=OU_ADDR1
This expression evaluates to true
exactly there is at least one OU_NAME
child of the current node and one OU_ADDR1
child of the current node with the same string value.
Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt
, le
, eq
, gt
, ge
and the inherited from XPath 1.0 general comparison operator =
.
Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.
If the one to many relationship is from T1 to T2 then it doesn't represent a function and therefore cannot be used to deduce or infer an inverse function that guarantees the resulting T2 value doesn't omit tuples of T1 join T2 that are deductively valid, because there is no deductively valid inverse function. ( representing functions was the purpose of primary keys. ) The answer in SQL think is yes you can do it. The answer in relational think is no you can't do it. See points of ambiguity in Codd 1970. The relationship would have to be many-to-one from T1 to T2.
HTML
alone does not support this. You need to use some JS
.
And also consider nowadays people use popup blocker in browsers.
<a href="javascript:window.open('document.aspx','mypopuptitle','width=600,height=400')">open popup</a>
GROUP BY YEAR(record_date), MONTH(record_date)
Check out the date and time functions in MySQL.
we can use Outputstream to output our Object to internal memory. And convert to string then save in preference. For example:
mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = mPrefs.edit();
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutput;
try {
objectOutput = new ObjectOutputStream(arrayOutputStream);
objectOutput.writeObject(object);
byte[] data = arrayOutputStream.toByteArray();
objectOutput.close();
arrayOutputStream.close();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Base64OutputStream b64 = new Base64OutputStream(out, Base64.DEFAULT);
b64.write(data);
b64.close();
out.close();
ed.putString(key, new String(out.toByteArray()));
ed.commit();
} catch (IOException e) {
e.printStackTrace();
}
when we need to extract Object from Preference. Use the code as below
byte[] bytes = mPrefs.getString(indexName, "{}").getBytes();
if (bytes.length == 0) {
return null;
}
ByteArrayInputStream byteArray = new ByteArrayInputStream(bytes);
Base64InputStream base64InputStream = new Base64InputStream(byteArray, Base64.DEFAULT);
ObjectInputStream in;
in = new ObjectInputStream(base64InputStream);
MyObject myObject = (MyObject) in.readObject();
I might've over-engineered my own solution without realizing that Type.valueOf("enum string")
actually existed.
I guess it gives more granular control but I'm not sure it's really necessary.
public enum Type {
DEBIT,
CREDIT;
public static Map<String, Type> typeMapping = Maps.newHashMap();
static {
typeMapping.put(DEBIT.name(), DEBIT);
typeMapping.put(CREDIT.name(), CREDIT);
}
public static Type getType(String typeName) {
if (typeMapping.get(typeName) == null) {
throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
}
return typeMapping.get(typeName);
}
}
I guess you're exchanging IllegalArgumentException
for RuntimeException
(or whatever exception you wish to throw) which could potentially clean up code.
Suppose logical address space is **32 bit so total possible logical entries will be 2^32 and other hand suppose each page size is 4 byte then size of one page is *2^2*2^10=2^12...* now we know that no. of pages in page table is pages=total possible logical address entries/page size so pages=2^32/2^12 =2^20 Now suppose that each entry in page table takes 4 bytes then total size of page table in *physical memory will be=2^2*2^20=2^22=4mb***
I was executing a get request an also want to see just the response and nothing else, seems like magic is done with -silent,-s option.
From the curl man page:
-s, --silent Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute. It will still output the data you ask for, potentially even to the terminal/stdout unless you redirect it.
Below the examples:
curl -s "http://host:8080/some/resource"
curl -silent "http://host:8080/some/resource"
Using custom headers
curl -s -H "Accept: application/json" "http://host:8080/some/resource")
Using POST method with a header
curl -s -X POST -H "Content-Type: application/json" "http://host:8080/some/resource") -d '{ "myBean": {"property": "value"}}'
You can also customize the output for specific values with -w, below the options I use to get just response codes of the curl:
curl -s -o /dev/null -w "%{http_code}" "http://host:8080/some/resource"
This works for me
If you migrated .htaccess file from public directory to project folder and altered server.php to index.php in project folder then this should works for you.
<link rel="stylesheet" href="{{ asset('public/css/app.css') }}" type="text/css">
Thanks
The default HTML editor (for static HTML) doesn't have a design view. To set the default editor to the Web forms editor which does have a design view,
Open with
HTML (web forms) editor
Set as default
OK
buttonOnce you have done that, all you need to do is click on design
or split
view as shown below:
Use Series.view
for convert boolean to integers:
df["somecolumn"] = df["somecolumn"].view('i1')
var fs = require("fs");
function readFileLineByLine(filename, processline) {
var stream = fs.createReadStream(filename);
var s = "";
stream.on("data", function(data) {
s += data.toString('utf8');
var lines = s.split("\n");
for (var i = 0; i < lines.length - 1; i++)
processline(lines[i]);
s = lines[lines.length - 1];
});
stream.on("end",function() {
var lines = s.split("\n");
for (var i = 0; i < lines.length; i++)
processline(lines[i]);
});
}
var linenumber = 0;
readFileLineByLine(filename, function(line) {
console.log(++linenumber + " -- " + line);
});
I caution against using the command
setx PATH "%PATH%;C:\Something\bin"
to modify the PATH variable because of a "feature" of its implementation. On many (most?) installations these days the variable will be lengthy - setx
will truncate the stored string to 1024 bytes, potentially corrupting the PATH (see the discussion here).
(I signed up specifically to flag this issue, and so lack the site reputation to directly comment on the answer posted on May 2 '12. My thanks to beresfordt for adding such a comment)
Mark color: #005580;
as color: #005580 !important;
.
It will override default bootstrap hover.
Release notes iOS 3.2 (External Display Support) and iOS 4.0 (Inherited Improvements) mentions that it should be possible to connect external displays to iOS 4.0 devices.
But you still have to jailbreak if you would mirror your iPhone screen...
Related SO Question with updates
RxJS Operators are functions that build on the observables foundation to enable sophisticated manipulation of collections.
For example, RxJS defines operators such as map()
, filter()
, concat()
, and flatMap()
.
You can use pipes to link operators together. Pipes let you combine multiple functions into a single function.
The pipe()
function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
I needed to have timezone information in my date string. I was originally using moment.tz(dateStr, 'America/New_York').toString();
but then I started getting errors about feeding that string back into moment.
I tried the moment.tz(dateStr, 'America/New_York').toDate();
but then I lost timezone information which I needed.
The only solution that returned a usable date string with timezone that could be fed back into moment was moment.tz(dateStr, 'America/New_York').format();
Rather than using sub queries in where condition which will increase the query time where records are huge.
I would suggest to use Inner Join as a better option to this problem.
Considering the same table this could give the result
SELECT EmailAddress, CustomerName FROM Customers as a
Inner Join Customers as b on a.CustomerName <> b.CustomerName and a.EmailAddress = b.EmailAddress
For still better results I would suggest you to use CustomerID
or any unique field of your table. Duplication of CustomerName
is possible.
The purpose of BASE64 encoding is to take binary data and be able to persist that to a string. That benefit comes at a cost, an increase in the size of the result (I think it's a 4 to 3 ratio). There are two solutions. If you know the data will be well formed XML, include it directly. The other, an better option, is to include the HTML in a CDATA section within an element within the XML.
I have a Samsung Duos device with Android 4.4.4 and the method suggested by Seetha in the accepted answer (i.e. call getDeviceIdDs) does not work for me, as the method does not exist. I was able to recover all the information I needed by calling method "getDefault(int slotID)", as shown below:
public static void samsungTwoSims(Context context) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try{
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getFirstMethod = telephonyClass.getMethod("getDefault", parameter);
Log.d(TAG, getFirstMethod.toString());
Object[] obParameter = new Object[1];
obParameter[0] = 0;
TelephonyManager first = (TelephonyManager) getFirstMethod.invoke(null, obParameter);
Log.d(TAG, "Device Id: " + first.getDeviceId() + ", device status: " + first.getSimState() + ", operator: " + first.getNetworkOperator() + "/" + first.getNetworkOperatorName());
obParameter[0] = 1;
TelephonyManager second = (TelephonyManager) getFirstMethod.invoke(null, obParameter);
Log.d(TAG, "Device Id: " + second.getDeviceId() + ", device status: " + second.getSimState()+ ", operator: " + second.getNetworkOperator() + "/" + second.getNetworkOperatorName());
} catch (Exception e) {
e.printStackTrace();
}
}
Also, I rewrote the code that iteratively tests for methods to recover this information so that it uses an array of method names instead of a sequence of try/catch. For instance, to determine if we have two active SIMs we could do:
private static String[] simStatusMethodNames = {"getSimStateGemini", "getSimState"};
public static boolean hasTwoActiveSims(Context context) {
boolean first = false, second = false;
for (String methodName: simStatusMethodNames) {
// try with sim 0 first
try {
first = getSIMStateBySlot(context, methodName, 0);
// no exception thrown, means method exists
second = getSIMStateBySlot(context, methodName, 1);
return first && second;
} catch (GeminiMethodNotFoundException e) {
// method does not exist, nothing to do but test the next
}
}
return false;
}
This way, if a new method name is suggested for some device, you can simply add it to the array and it should work.
Functionally, you use public/private key encryption to make certain only the receiver can read your message. The message is encrypted using the public key of the receiver and decrypted using the private key of the receiver.
Signing you can use to let the receiver know you created the message and it has not changed during transfer. Message signing is done using your own private key. The receiver can use your public key to check the message has not been tampered.
As for the algorithm used: that involves a one-way function see for example wikipedia. One of the first of such algorithms use large prime-numbers but more one-way functions have been invented since.
Search for 'Bob', 'Alice' and 'Mallory' to find introduction articles on the internet.
use the className
property:
document.getElementById('your_element_s_id').className = 'cssClass';
HTML and XML entities are just a way of referencing a Unicode code-point in a way that reliably works regardless of the encoding of the actual page, making them useful for using esoteric Unicode characters in a page using 7-bit ASCII or some other encoding scheme, ideally on a one-off basis. They're also used to escape the <
, >
, "
and &
characters as these are reserved in SGML.
Anyway, Unicode has a number of tick/check characters, as per Wikipedia ( http://en.wikipedia.org/wiki/Tick_(check_mark) ).
Ideally you should save/store your HTML in a Unicode format like UTF-8 or 16, thus obviating the need to use HTML entities to represent a Unicode character. Nonetheless use: ✔
✔.
✔
✔
Is using hex notation and is the same as
$#10004;
(as 2714
in base 16 is the same as 10004
in base 10)
The problem was caused by not setting the CUDA_VISIBLE_DEVICES
variable within the shell correctly.
To specify CUDA device 1
for example, you would set the CUDA_VISIBLE_DEVICES
using
export CUDA_VISIBLE_DEVICES=1
or
CUDA_VISIBLE_DEVICES=1 ./cuda_executable
The former sets the variable for the life of the current shell, the latter only for the lifespan of that particular executable invocation.
If you want to specify more than one device, use
export CUDA_VISIBLE_DEVICES=0,1
or
CUDA_VISIBLE_DEVICES=0,1 ./cuda_executable
You basically need to run the installation again to rebuild the master
database with the new collation. You cannot change the entire server's collation any other way.
See:
Update: if you want to change the collation of a database, you can get the current collation using this snippet of T-SQL:
SELECT name, collation_name
FROM sys.databases
WHERE name = 'test2' -- put your database name here
This will yield a value something like:
Latin1_General_CI_AS
The _CI
means "case insensitive" - if you want case-sensitive, use _CS
in its place:
Latin1_General_CS_AS
So your T-SQL command would be:
ALTER DATABASE test2 -- put your database name here
COLLATE Latin1_General_CS_AS -- replace with whatever collation you need
You can get a list of all available collations on the server using:
SELECT * FROM ::fn_helpcollations()
You can see the server's current collation using:
SELECT SERVERPROPERTY ('Collation')
I have encountered this issue in Angular 5 which still followed the link. The solution was to have the function return false
in order to prevent the page being refreshed:
<a href="" (click)="openChangePasswordForm()">Change expired password</a>
openChangePasswordForm(): boolean {
console.log("openChangePasswordForm called!");
return false;
}
For me none of the packages mentioned above did help.
I finally managed to install lxml
after running:
sudo apt-get install python3.5-dev
Use the remove/erase idiom:
std::vector<int>& vec = myNumbers; // use shorter name
vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end());
What happens is that remove
compacts the elements that differ from the value to be removed (number_in
) in the beginning of the vector
and returns the iterator to the first element after that range. Then erase
removes these elements (whose value is unspecified).
An alternative solution to that of @Aaron is the bquote()
function. We need to supply a valid R expression, in this case LABEL ~ x^2
for example, where LABEL
is the string you want to assign from the vector labNames
. bquote
evaluates R code within the expression wrapped in .( )
and subsitutes the result into the expression.
Here is an example:
labNames <- c('xLab','yLab')
xlab <- bquote(.(labNames[1]) ~ x^2)
ylab <- bquote(.(labNames[2]) ~ y^2)
plot(c(1:10), xlab = xlab, ylab = ylab)
(Note the ~
just adds a bit of spacing, if you don't want the space, replace it with *
and the two parts of the expression will be juxtaposed.)
Minor variation to user1850980's answer (for the question "How to initialize a list of empty dictionaries") using list constructor:
dictlistGOOD = list( {} for i in xrange(listsize) )
I found out to my chagrin, this does NOT work:
dictlistFAIL = [{}] * listsize # FAIL!
as it creates a list of references to the same empty dictionary, so that if you update one dictionary in the list, all the other references get updated too.
Try these updates to see the difference:
dictlistGOOD[0]["key"] = "value"
dictlistFAIL[0]["key"] = "value"
(I was actually looking for user1850980's answer to the question asked, so his/her answer was helpful.)
In Oracle 12c you can also declare an identity column
CREATE TABLE identity_test_tab (
id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
description VARCHAR2(30)
);
examples & performance tests here ... where, is shorts, the conclusion is that the direct use of the sequence or the new identity column are much faster than the triggers.
svn revert -R .
svn cleanup . --remove-unversioned
As Martin Smith said, if you have no access to the machine or the filesystem, you will need to use third party tools, like Red Gate or Adept to do a compare on the source and destination systems. Red Gate's tools will allow you to copy the objects and schemas AND the data.
A shell convention is that a successful executable should exit with the value 0. Anything else can be interpreted as a failure of some sort, on part of bash or the executable you that just ran. See also $PIPESTATUS and the EXIT STATUS section of the bash man page:
For the shell’s purposes, a command which exits with a zero exit status has succeeded. An exit status of zero indicates success. A non-zero exit status indicates failure. When a command terminates on a fatal signal N, bash uses the value of 128+N as the exit status.
If a command is not found, the child process created to execute it returns a status of 127. If a com-
mand is found but is not executable, the return status is 126.
If a command fails because of an error during expansion or redirection, the exit status is greater than
zero.
Shell builtin commands return a status of 0 (true) if successful, and non-zero (false) if an error
occurs while they execute. All builtins return an exit status of 2 to indicate incorrect usage.
Bash itself returns the exit status of the last command executed, unless a syntax error occurs, in
which case it exits with a non-zero value. See also the exit builtin command below.
var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
console.log(key + ': ' + value);
});
yields the attributes of obj
with their respective values:
name: Krishna
gender: male
$('.toggle img').data('block', 'something').attr('src', 'something.jpg');
var secondEmails = (from item in list2
select new { Email = item.Email }
).ToList();
var matches = from item in list1
where !secondEmails.Contains(item.Email)
select new {Email = item.Email};
How about something like this:
var MyNamespace = {
convertToBoolean: function (value) {
//VALIDATE INPUT
if (typeof value === 'undefined' || value === null) return false;
//DETERMINE BOOLEAN VALUE FROM STRING
if (typeof value === 'string') {
switch (value.toLowerCase()) {
case 'true':
case 'yes':
case '1':
return true;
case 'false':
case 'no':
case '0':
return false;
}
}
//RETURN DEFAULT HANDLER
return Boolean(value);
}
};
Then you can use it like this:
MyNamespace.convertToBoolean('true') //true
MyNamespace.convertToBoolean('no') //false
MyNamespace.convertToBoolean('1') //true
MyNamespace.convertToBoolean(0) //false
I have not tested it for performance, but converting from type to type should not happen too often otherwise you open your app up to instability big time!
Your syntax is fine, it will return rows where LastAdDate
lies within the last 6 months;
select cast('01-jan-1970' as datetime) as LastAdDate into #PubAdvTransData
union select GETDATE()
union select NULL
union select '01-feb-2010'
DECLARE @sp_Date DATETIME = DateAdd(m, -6, GETDATE())
SELECT * FROM #PubAdvTransData pat
WHERE (pat.LastAdDate > @sp_Date)
>2010-02-01 00:00:00.000
>2010-04-29 21:12:29.920
Are you sure LastAdDate
is of type DATETIME
?
Easy way to get the text inside of the editor or the length of it :)
var editorText = CKEDITOR.instances['<%= your_editor.ClientID %>'].getData();
alert(editorText);
var editorTextLength = CKEDITOR.instances['<%= your_editor.ClientID %>'].getData().length;
alert(editorTextLength);
Try:
SELECT
*
FROM
YourTable
WHERE
CHAR_LENGTH(Link) > x
The simplest way is this:
while (cursor.moveToNext()) {
...
}
The cursor starts before the first result row, so on the first iteration this moves to the first result if it exists. If the cursor is empty, or the last row has already been processed, then the loop exits neatly.
Of course, don't forget to close the cursor once you're done with it, preferably in a finally
clause.
Cursor cursor = db.rawQuery(...);
try {
while (cursor.moveToNext()) {
...
}
} finally {
cursor.close();
}
If you target API 19+, you can use try-with-resources.
try (Cursor cursor = db.rawQuery(...)) {
while (cursor.moveToNext()) {
...
}
}
Kotlin code:
Start the SecondActivity
:
startActivity(Intent(context, SecondActivity::class.java)
.putExtra(SecondActivity.PARAM_GAME_ID, gameId))
Get the Id in SecondActivity
:
class CaptureActivity : AppCompatActivity() {
companion object {
const val PARAM_GAME_ID = "PARAM_GAME_ID"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val gameId = intent.getStringExtra(PARAM_GAME_ID)
// TODO use gameId
}
}
where gameId
is String?
(can be null)
You all seem to love complication. Just click on column(to select entire column), press and hold CTRL and click on cells that you want to exclude(C1 to C5 in you case). Now you have selected entire column C (right to the end of sheet) without starting cells. All you have to do now is to rightclick and "Define Name" for your selection(ex. asdf ). In formula you use SUM(asdf). And now you're done. Good luck
Allways find the easyest way ;)
I'm suggest that you learn about Jquery, most popular JS library. With jquery it's simple to acomplish what you want.Simle example below:
$(“#DIV_YOU_WANT_CHANGE”).click(function() {
$(this).addClass(“.your_class_with_new_color”);
});
For the class below:
public class Page
{
private string data;
public Page()
{
}
public Page(string data)
{
this.Data = data;
}
public string Data
{
get
{
return this.data;
}
set
{
this.data = value;
}
}
}
you can initialize the array of above object as below.
Pages = new Page[] { new Page("a string") };
Hope this helps.
[Update Sep 2016]: This answer was intended for docker compose file v1 (as shown by the sample compose file below). For v2, see the other answer by @Windsooon.
[Original answer]:
It is pretty clear in the documentation. depends_on
decides the dependency and the order of container creation and links
not only does these, but also
Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.
For example, assuming the following docker-compose.yml
file:
web:
image: example/my_web_app:latest
links:
- db
- cache
db:
image: postgres:latest
cache:
image: redis:latest
With links
, code inside web
will be able to access the database using db:5432
, assuming port 5432 is exposed in the db
image. If depends_on
were used, this wouldn't be possible, but the startup order of the containers would be correct.
You can add .a file in the linking command:
gcc yourfiles /path/to/library/libLIBRARY.a
But this is not talking with gcc driver, but with ld
linker as options like -Wl,anything
are.
When you tell gcc or ld -Ldir -lLIBRARY
, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose
). To change order of library types checked you can use -Wl,-Bstatic
and -Wl,-Bdynamic
. Here is a man page of gnu LD: http://linux.die.net/man/1/ld
To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:
gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3
Assuming that default setting of ld is to use dynamic libraries (it is on Linux).
The BLOB datatype is best for storing files.
Looks like the connect-auth plugin to the connect middleware is exactly what I need
I'm using express [ http://expressjs.com ] so the connect plugin fits in very nicely since express is subclassed (ok - prototyped) from connect
A While
/Wend
loop can only be exited prematurely with a GOTO
or by exiting from an outer block (Exit sub
/function
or another exitable loop)
Change to a Do
loop instead:
Do While True
count = count + 1
If count = 10 Then
Exit Do
End If
Loop
Or for looping a set number of times:
for count = 1 to 10
msgbox count
next
(Exit For
can be used above to exit prematurely)
You could also just change the @RequestParam default required status to false so that HTTP response status code 400 is not generated. This will allow you to place the Annotations in any order you feel like.
@RequestParam(required = false)String name
Function:
#include <string>
std::string
basename(const std::string &filename)
{
if (filename.empty()) {
return {};
}
auto len = filename.length();
auto index = filename.find_last_of("/\\");
if (index == std::string::npos) {
return filename;
}
if (index + 1 >= len) {
len--;
index = filename.substr(0, len).find_last_of("/\\");
if (len == 0) {
return filename;
}
if (index == 0) {
return filename.substr(1, len - 1);
}
if (index == std::string::npos) {
return filename.substr(0, len);
}
return filename.substr(index + 1, len - index - 1);
}
return filename.substr(index + 1, len - index);
}
Tests:
#define CATCH_CONFIG_MAIN
#include <catch/catch.hpp>
TEST_CASE("basename")
{
CHECK(basename("") == "");
CHECK(basename("no_path") == "no_path");
CHECK(basename("with.ext") == "with.ext");
CHECK(basename("/no_filename/") == "no_filename");
CHECK(basename("no_filename/") == "no_filename");
CHECK(basename("/no/filename/") == "filename");
CHECK(basename("/absolute/file.ext") == "file.ext");
CHECK(basename("../relative/file.ext") == "file.ext");
CHECK(basename("/") == "/");
CHECK(basename("c:\\windows\\path.ext") == "path.ext");
CHECK(basename("c:\\windows\\no_filename\\") == "no_filename");
}
TextView txtvw = (TextView)findViewById(R.id.TextView01);
txtvw.setText(readTxt());
private String readTxt()
{
InputStream raw = getResources().openRawResource(R.raw.hello);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try
{
i = raw.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = raw.read();
}
raw.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
TextView01:: txtview in linearlayout hello:: .txt file in res/raw folder (u can access ny othr folder as wel)
Ist 2 lines are 2 written in onCreate() method
rest is to be written in class extending Activity!!
This is the proper way to access data in laravel :
@foreach($data-> ac as $link)
{{$link->url}}
@endforeach
in VB.net
My.Application.Info.DirectoryPath
works for me (Application Type: Class Library). Not sure about C#... Returns the path w/o Filename as string
SELECT TABLE_NAME AS table_name,
table_rows AS QuantofRows,
ROUND((data_length + index_length) /1024, 2 ) AS total_size_kb
FROM information_schema.TABLES
WHERE information_schema.TABLES.table_schema = 'db'
ORDER BY (data_length + index_length) DESC;
all 2 above is tested on mysql
Some explanation (at least for Fragments - never tried with pure Activity). Hope it helps someone to understand Android better.
Most popular answer by Arun George is correct but don't work in some cases.
The answer by Marco HC uses Runnable wich is a last resort due to additional CPU load.
The answer is - you should simply choose correct place to call to setSelection(), for example it works for me:
@Override
public void onResume() {
super.onResume();
yourSpinner.setSelection(pos);
}
But it won't work in onCreateView(). I suspect that is the reason for the interest to this topic.
The secret is that with Android you can't do anything you want in any method - oops:( - components may just not be ready. As another example - you can't scroll ScrollView neither in onCreateView() nor in onResume() (see the answer here)
Had the same problem:
$params = array('redirect_uri' => 'facebook.com/pages/foobar-dev');
$facebook->getLoginUrl($params);
When I changed the redirect_uri from the devloper page to the live page, 191 Error came up.
So I deleted the $params:
$facebook->getLoginUrl();
After the app-request now FB redirects to the app url itself f.e.: my.domain.com
What I do now is checking in index.php of my app if I'm inside FB iframe or not. If not I redirect to the live FB page f.e.:
$app = 'facebook.com/pages/foobar-live';
$rd = (isset($_SERVER['HTTP_REFERER'])) ? parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) : false;
if ($rd == 'apps.facebook.com' || (!isset($_REQUEST['signed_request']))) {
echo '<script>window.parent.location = "'.$app.'";</script>';
die();
}
On Mac (on french keyboard its) cmd + shift + F
1 & 2: innerHTML can take HTML as well as text. You could do something like:
c1.innerHTML = "<input size=25 type=\"text\" id='newID' readonly=true/>";
May or may not be the best way to do it, but you could do it that way.
3: I would just use a global variable that holds the number of POIs and increment/decrement it each time.
The Timeout property specifies the time-out period assigned to the Session object for the application, in minutes. If the user does not refresh or request a page within the time-out period, the session ends.
IIS 6.0: The minimum allowed value is 1 minute and the maximum is 1440 minutes.
Session.Timeout = 600;
This looks like a CSV file, so you could use the python csv module to read it. For example:
import csv
crimefile = open(fileName, 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]
Using the csv module allows you to specify how things like quotes and newlines are handled. See the documentation I linked to above.
None of this worked in my specific instance. What did was changing to a NetBIOS name from the FQDN.
Instead of:
\\server.domain.net\file.ps1
use:
\\server\file.ps1
Using the name bypasses the "automatically detect intranet network" config in IE.
See Option 1 in the blog here: http://setspn.blogspot.com/2011/05/running-powershell-scripts-from-unc.html
Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.
To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency
or UIViewRoot#addComponentResource()
) the following way:
<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />
It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.
This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css
resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css
, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.
Also, when you're using a custom ResourceHandler
, you can also apply more finer grained control over resources coming from a specific library when library
is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler
ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler
and GraphicResourceHandler
; check the createResource()
method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource
or GraphicResource
for the purpose.
Noted should be that RichFaces did it wrong. It didn't use any library
at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander
had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.
Your own webapp does not necessarily need a resource library. You'd best just omit it.
<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />
Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml
template file:
<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />
And a /WEB-INF/templates/admin.xhtml
template file:
<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />
For a real world example, check the OmniFaces showcase source code.
Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib
, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):
<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />
Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)*
pattern to denote the resource library version.
WebContent
|-- resources
| `-- default
| `-- 1_0
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
When using this markup:
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
This will generate the following HTML with the library version as v
parameter:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_0" alt="" />
So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler
will automatically serve the resource from the highest version number, according to numerical ordering rules.
So, when copying/renaming resources/default/1_0/*
folder into resources/default/1_1/*
like follows:
WebContent
|-- resources
| `-- default
| |-- 1_0
| | :
| |
| `-- 1_1
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
Then the last markup example would generate the following HTML:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_1" alt="" />
This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.
Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler
. See also How to use JSF versioning for resources in jar.
Sweet alerts also has an 'html' option, set it to true.
var hh = "<b>test</b>";
swal({
title: "" + txt + "",
html: true,
text: "Testno sporocilo za objekt " + hh + "",
confirmButtonText: "V redu",
allowOutsideClick: "true"
});
I've got a solution that's pretty simple to implement.
Make a temporary class just to wrap the list object and later call the value from the class.
Here's a practical example:
df = pd.DataFrame([
{'a': 1},
{'a': 2},
{'a': 3},
])
df.loc[:, 'b'] = [
[1,2,4,2,],
[1,2,],
[4,5,6]
] # This works. Because the list has the same length as the rows of the dataframe
df.loc[:, 'c'] = [1,2,4,5,3] # This does not work.
>>> ValueError: Must have equal len keys and value when setting with an iterable
## To force pandas to have list as value in each cell, wrap the list with a temporary class.
class Fake(object):
def __init__(self, li_obj):
self.obj = li_obj
df.loc[:, 'c'] = Fake([1,2,5,3,5,7,]) # This works.
df.c = df.c.apply(lambda x: x.obj) # Now extract the value from the class. This works.
Creating a fake class to do this might look like a hassle but it can have some practical applications. For an example you can use this with apply
when the return value is list.
Pandas would normally refuse to insert list into a cell but if you use this method, you can force the insert.
The problem is in the import
line. You are importing a module, not a class. Assuming your file is named other_file.py
(unlike java, again, there is no such rule as "one class, one file"):
from other_file import findTheRange
if your file is named findTheRange too, following java's convenions, then you should write
from findTheRange import findTheRange
you can also import it just like you did with random
:
import findTheRange
operator = findTheRange.findTheRange()
Some other comments:
a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)
b) You can build the list directly:
randomList = [random.randint(0, 100) for i in range(5)]
c) You can call methods in the same way you do in java:
largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)
d) You can use built in function, and the huge python library:
largestInList = max(randomList)
smallestInList = min(randomList)
e) If you still want to use a class, and you don't need self
, you can use @staticmethod
:
class findTheRange():
@staticmethod
def findLargest(_list):
#stuff...
If you know the width is 400px this would be the easiest way to do it I guess.
left: calc(50% - 200px);
I had same problem. It was resolved by following css line;
h1{margin-top:0px}
My main div contained h1
tag in the beginning.
On Windows 7 , the only thing that worked for me is this. Go to Device Manager -> Under Android Phone -> Right Click and select 'enable'
You could also set between two dates:
Delete From tblAudit
WHERE Date_dat < DATEADD(day, -360, GETDATE())
GO
Delete From tblAudit
WHERE Date_dat > DATEADD(day, -60, GETDATE())
GO
According to mozilla:
A Map object can iterate its elements in insertion order - a for..of loop will return an array of [key, value] for each iteration.
and
Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this, Objects have been used as Maps historically; however, there are important differences between Objects and Maps that make using a Map better.
An Object has a prototype, so there are default keys in the map. However, this can be bypassed using map = Object.create(null). The keys of an Object are Strings, where they can be any value for a Map. You can get the size of a Map easily while you have to manually keep track of size for an Object.
Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.
Use objects when there is logic that operates on individual elements.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
The iterability-in-order is a feature that has long been wanted by developers, in part because it ensures the same performance in all browsers. So to me that's a big one.
The myMap.has(key)
method will be especially handy, and also the myMap.size
property.
There are two issues here.
Firstly, you can't use the []
syntax like you may be able to in other languages. Square brackets only apply to arrays in Java, and so can only be used with integer indexes.
data.put
is correct but that is a statement and so must exist in a method block. Only field declarations can exist at the class level. Here is an example where everything is within the local scope of a method:
public class Data {
public static void main(String[] args) {
Map<String, String> data = new HashMap<String, String>();
data.put("John", "Taxi Driver");
data.put("Mark", "Professional Killer");
}
}
If you want to initialize a map as a static field of a class then you can use Map.of
, since Java 9:
public class Data {
private static final Map<String, String> DATA = Map.of("John", "Taxi Driver");
}
Before Java 9, you can use a static initializer block to accomplish the same thing:
public class Data {
private static final Map<String, String> DATA = new HashMap<>();
static {
DATA.put("John", "Taxi Driver");
}
}
Check for the name of the
templates
folder. it should be templates not template(without s).
How about HKEY_CLASSES_ROOT\Word.Application\CurVer?
list = [1, 2, 3, 4, 5]
for i in list[0:-1]:
print(i, end=', ')
print(list[-1])
do for loops really take that much longer to run?
was trying to make something that printed all str values in a list separated by commas, inserting "and" before the last entry and came up with this:
spam = ['apples', 'bananas', 'tofu', 'cats']
for i in spam[0:-1]:
print(i, end=', ')
print('and ' + spam[-1])
We do all our enums like this when it comes to Rest/Json etc. It has the advantage that the error is human readable and also gives you the accepted value list. We are using a custom method MyEnum.fromString instead of MyEnum.valueOf, hope it helps.
public enum MyEnum {
A, B, C, D;
private static final Map<String, MyEnum> NAME_MAP = Stream.of(values())
.collect(Collectors.toMap(MyEnum::toString, Function.identity()));
public static MyEnum fromString(final String name) {
MyEnum myEnum = NAME_MAP.get(name);
if (null == myEnum) {
throw new IllegalArgumentException(String.format("'%s' has no corresponding value. Accepted values: %s", name, Arrays.asList(values())));
}
return myEnum;
}
}
so for example if you call
MyEnum value = MyEnum.fromString("X");
you'll get an IllegalArgumentException with the following message:
'X' has no corresponding value. Accepted values: [A, B, C, D]
you can change the IllegalArgumentException to a custom one.
Just a word on drawing (incorrect) conclusions from any of the performance measurement commands referred to in the answers. There are a number of pitfalls that should taken in consideration aside from looking to the bare invocation time of a (custom) function or command.
'Sjoemelsoftware' voted Dutch word of the year 2015
Sjoemelen means cheating, and the word sjoemelsoftware came into being due to the Volkswagen emissions scandal. The official definition is "software used to influence test results".
Personally, I think that "Sjoemelsoftware" is not always deliberately created to cheat test results but might originate from accommodating practical situation that are similar to test cases as shown below.
As an example, using the listed performance measurement commands, Language Integrated Query (LINQ)(1), is often qualified as the fasted way to get something done and it often is, but certainly not always! Anybody who measures a speed increase of a factor 40 or more in comparison with native PowerShell commands, is probably incorrectly measuring or drawing an incorrect conclusion.
The point is that some .Net classes (like LINQ) using a lazy evaluation (also referred to as deferred execution(2)). Meaning that when assign an expression to a variable, it almost immediately appears to be done but in fact it didn't process anything yet!
Let presume that you dot-source your . .\Dosomething.ps1
command which has either a PowerShell or a more sophisticated Linq expression (for the ease of explanation, I have directly embedded the expressions directly into the Measure-Command
):
$Data = @(1..100000).ForEach{[PSCustomObject]@{Index=$_;Property=(Get-Random)}}
(Measure-Command {
$PowerShell = $Data.Where{$_.Index -eq 12345}
}).totalmilliseconds
864.5237
(Measure-Command {
$Linq = [Linq.Enumerable]::Where($Data, [Func[object,bool]] { param($Item); Return $Item.Index -eq 12345})
}).totalmilliseconds
24.5949
The result appears obvious, the later Linq command is a about 40 times faster than the first PowerShell command. Unfortunately, it is not that simple...
Let's display the results:
PS C:\> $PowerShell
Index Property
----- --------
12345 104123841
PS C:\> $Linq
Index Property
----- --------
12345 104123841
As expected, the results are the same but if you have paid close attention, you will have noticed that it took a lot longer to display the $Linq
results then the $PowerShell
results.
Let's specifically measure that by just retrieving a property of the resulted object:
PS C:\> (Measure-Command {$PowerShell.Property}).totalmilliseconds
14.8798
PS C:\> (Measure-Command {$Linq.Property}).totalmilliseconds
1360.9435
It took about a factor 90 longer to retrieve a property of the $Linq
object then the $PowerShell
object and that was just a single object!
Also notice an other pitfall that if you do it again, certain steps might appear a lot faster then before, this is because some of the expressions have been cached.
Bottom line, if you want to compare the performance between two functions, you will need to implement them in your used case, start with a fresh PowerShell session and base your conclusion on the actual performance of the complete solution.
(1) For more background and examples on PowerShell and LINQ, I recommend tihis site: High Performance PowerShell with LINQ
(2) I think there is a minor difference between the two concepts as with lazy evaluation the result is calculated when needed as apposed to deferred execution were the result is calculated when the system is idle
If you have the cursor on a method then CTRL+SHIFT+I will popup the method implementation. If the method is an interface
method, then you can use up- and down- arrows to cycle through the implementations:
Map<String, Integer> m = ...
m.contains|Key("Wibble");
Where | is (for example) where your cursor is.
Missing a semicolon
if [ -a myApp ];
then
rm myApp
fi
However, I assume you are checking for existence before deletion to prevent an error message. If so, you can just use rm -f myApp
which "forces" delete, i.e. doesn't error out if the file didn't exist.
If it is VIM for Windows, you can do the following:
:wq
Enter or ZZ
.Note that in VIM there are often several ways to do one thing. Here there is a slight difference though. :wq
Enter always writes the current file before closing it, while ZZ
, :x
Enter, :xi
Enter, :xit
Enter, :exi
Enter and :exit
Enter only write it if the document is modified.
All these synonyms just have different numbers of keypresses.
Appending single space to output file with stream variable.
// declare output file stream varaible and open file
ofstream fout;
fout.open("flux_capacitor.txt");
fout << var << " ";
Another way would be adding __getitem__, __setitem__ function
def __getitem__(self, key):
return getattr(self, key)
You can use self[key] to access now.
Recommended way for versions of PHP >= 5.4.0 , PHP 7
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
Reference: http://www.php.net/manual/en/function.session-status.php
For versions of PHP < 5.4.0
if(session_id() == '') {
session_start();
}
SqlParameters[1] = new SqlParameter("Date1", SqlDbType.SqlDateTime);
SqlParameters[1].Value = DBNull.Value;
SqlParameters[1].Direction = ParameterDirection.Input;
...then copy for the second.
Simple, right click on your project in Android Studio, then click on the Optimize Imports that should work.
To do same thing which I described above, you can do same just pressing Ctrl+Alt+O, it will optimize imports of your current file and your entire project depends on your selection in a dialog.
func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
let share = UITableViewRowAction(style: .normal, title: "Share") { action, index in
//handle like delete button
print("share button tapped")
}
share.backgroundColor = .lightGray
let delete = UITableViewRowAction(style: .normal, title: "Delete") { action, index in
self.nameArray.remove(at: editActionsForRowAt.row)
self.swipeTable.beginUpdates()
self.swipeTable.deleteRows(at: [editActionsForRowAt], with: .right)
self.swipeTable.endUpdates()
print("delete button tapped")
}
delete.backgroundColor = .orange
return [share,delete]
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
Running adb commands on all connected devices
Create a bash (adb+)
adb devices | while read line
do
if [ ! "$line" = "" ] && [ `echo $line | awk '{print $2}'` = "device" ]
then
device=`echo $line | awk '{print $1}'`
echo "$device $@ ..."
adb -s $device $@
fi
done use it with
adb+ //+ command
You can use shared preferences from flutter's official plugins. https://github.com/flutter/plugins/tree/master/packages/shared_preferences
It uses Shared Preferences for Android, NSUserDefaults for iOS.
For me, turns out I was setting Access-Control-Allow-Origin
response header to a specific (and the correct) host.com
but it had to be returned as http://host.com
instead. What does firefox do? It silently swallows the GET request and returns a status 0 to the XHR, with no warnings output to the javascript console, whereas for other similar failures it would at least say something. Ai ai.
Here's a light weight way to use require and exports in your web client. It's a simple wrapper that creates a "namespace" global variable, and you wrap your CommonJS compatible code in a "define" function like this:
namespace.lookup('org.mydomain.mymodule').define(function (exports, require) {
var extern = require('org.other.module');
exports.foo = function foo() { ... };
});
More docs here:
I recommend the following syntax for readability.
<? if ($condition): ?>
<p>Content</p>
<? elseif ($other_condition): ?>
<p>Other Content</p>
<? else: ?>
<p>Default Content</p>
<? endif; ?>
Note, omitting php
on the open tags does require that short_open_tags
is enabled in your configuration, which is the default. The relevant curly-brace-free conditional syntax is always enabled and can be used regardless of this directive.
To follow up with what thomasfuchs said but instead for GitHub Enterprise users here's what you can use.
curl -H 'Authorization: token INSERTACCESSTOKENHERE' -H 'Accept: application/vnd.github.v3.raw' -O -L https://your_domain/api/v3/repos/owner/repo/contents/path
Also here's the API documentation https://developer.github.com/v3/repos/contents
There is also a solution:
http://www.welefen.com/php-unicode-to-utf8.html
function entity2utf8onechar($unicode_c){
$unicode_c_val = intval($unicode_c);
$f=0x80; // 10000000
$str = "";
// U-00000000 - U-0000007F: 0xxxxxxx
if($unicode_c_val <= 0x7F){ $str = chr($unicode_c_val); } //U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
else if($unicode_c_val >= 0x80 && $unicode_c_val <= 0x7FF){ $h=0xC0; // 11000000
$c1 = $unicode_c_val >> 6 | $h;
$c2 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2);
} else if($unicode_c_val >= 0x800 && $unicode_c_val <= 0xFFFF){ $h=0xE0; // 11100000
$c1 = $unicode_c_val >> 12 | $h;
$c2 = (($unicode_c_val & 0xFC0) >> 6) | $f;
$c3 = ($unicode_c_val & 0x3F) | $f;
$str=chr($c1).chr($c2).chr($c3);
}
//U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
else if($unicode_c_val >= 0x10000 && $unicode_c_val <= 0x1FFFFF){ $h=0xF0; // 11110000
$c1 = $unicode_c_val >> 18 | $h;
$c2 = (($unicode_c_val & 0x3F000) >>12) | $f;
$c3 = (($unicode_c_val & 0xFC0) >>6) | $f;
$c4 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2).chr($c3).chr($c4);
}
//U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if($unicode_c_val >= 0x200000 && $unicode_c_val <= 0x3FFFFFF){ $h=0xF8; // 11111000
$c1 = $unicode_c_val >> 24 | $h;
$c2 = (($unicode_c_val & 0xFC0000)>>18) | $f;
$c3 = (($unicode_c_val & 0x3F000) >>12) | $f;
$c4 = (($unicode_c_val & 0xFC0) >>6) | $f;
$c5 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2).chr($c3).chr($c4).chr($c5);
}
//U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if($unicode_c_val >= 0x4000000 && $unicode_c_val <= 0x7FFFFFFF){ $h=0xFC; // 11111100
$c1 = $unicode_c_val >> 30 | $h;
$c2 = (($unicode_c_val & 0x3F000000)>>24) | $f;
$c3 = (($unicode_c_val & 0xFC0000)>>18) | $f;
$c4 = (($unicode_c_val & 0x3F000) >>12) | $f;
$c5 = (($unicode_c_val & 0xFC0) >>6) | $f;
$c6 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2).chr($c3).chr($c4).chr($c5).chr($c6);
}
return $str;
}
function entities2utf8($unicode_c){
$unicode_c = preg_replace("/\&\#([\da-f]{5})\;/es", "entity2utf8onechar('\\1')", $unicode_c);
return $unicode_c;
}
Setting the objectEquality
parameter (third parameter) of the $watch
function is definitely the correct way to watch ALL properties of the array.
$scope.$watch('columns', function(newVal) {
alert('columns changed');
},true); // <- Right here
Piran answers this well enough and mentions $watchCollection
as well.
More Detail
The reason I'm answering an already answered question is because I want to point out that wizardwerdna's answer is not a good one and should not be used.
The problem is that the digests do not happen immediately. They have to wait until the current block of code has completed before executing. Thus, watch the length
of an array may actually miss some important changes that $watchCollection
will catch.
Assume this configuration:
$scope.testArray = [
{val:1},
{val:2}
];
$scope.$watch('testArray.length', function(newLength, oldLength) {
console.log('length changed: ', oldLength, ' -> ', newLength);
});
$scope.$watchCollection('testArray', function(newArray) {
console.log('testArray changed');
});
At first glance, it may seem like these would fire at the same time, such as in this case:
function pushToArray() {
$scope.testArray.push({val:3});
}
pushToArray();
// Console output
// length changed: 2 -> 3
// testArray changed
That works well enough, but consider this:
function spliceArray() {
// Starting at index 1, remove 1 item, then push {val: 3}.
$testArray.splice(1, 1, {val: 3});
}
spliceArray();
// Console output
// testArray changed
Notice that the resulting length was the same even though the array has a new element and lost an element, so as watch as the $watch
is concerned, length
hasn't changed. $watchCollection
picked up on it, though.
function pushPopArray() {
$testArray.push({val: 3});
$testArray.pop();
}
pushPopArray();
// Console output
// testArray change
The same result happens with a push and pop in the same block.
Conclusion
To watch every property in the array, use a $watch
on the array iteself with the third parameter (objectEquality) included and set to true. Yes, this is expensive but sometimes necessary.
To watch when object enter/exit the array, use a $watchCollection
.
Do NOT use a $watch
on the length
property of the array. There is almost no good reason I can think of to do so.
You will need to Build and Archive your project. You may need to check what code signing settings you have in the project and executable.
Use the Organiser to select your archive version and then you can Share that version of your project. You will need to select the correct code signing again. It will allow you to save the .ipa file where you want.
Drag and drop the .ipa file into iTunes and then sync with your iPhone.
He is asking about the real difference. When you are talking about undefined behavior you are on the level of guarantee provided by language specification - it's far from reality. To understand the real difference please check this snippet (of course this is UB but it's perfectly defined on your favorite compiler):
#include <stdio.h>
int main()
{
int i1 = ~0;
int i2 = i1 >> 1;
unsigned u1 = ~0;
unsigned u2 = u1 >> 1;
printf("int : %X -> %X\n", i1, i2);
printf("unsigned int: %X -> %X\n", u1, u2);
}
In some cases URL may start with "www". In this case you will get an exception:
android.content.ActivityNotFoundException: No Activity found to handle Intent
The URL must always start with "http://" or "https://" so I use this snipped of code:
if (!url.startsWith("https://") && !url.startsWith("http://")){
url = "http://" + url;
}
Intent openUrlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(openUrlIntent);
FLUSHALL Remove all keys from all databases
FLUSHDB Remove all keys from the current database
SCRIPT FLUSH Remove all the scripts from the script cache.
If the keystore contains other key-entries with different password you have to change them also or you can isolate your key to different keystore using below command,
keytool -importkeystore -srckeystore mystore.jck -destkeystore myotherstore.jks -srcstoretype jceks
-deststoretype jks -srcstorepass mystorepass -deststorepass myotherstorepass -srcalias myserverkey
-destalias myotherserverkey -srckeypass mykeypass -destkeypass myotherkeypass
//////////////////////////////////////////////////////
function ToInt(x){x=parseInt(x);return isNaN(x)?0:x;}
//////////////////////////////////////////////////////
var x = ToInt(''); //-> x=0
x = ToInt('abc') //-> x=0
x = ToInt('0.1') //-> x=0
x = ToInt('5.9') //-> x=5
x = ToInt(5.9) //-> x=5
x = ToInt(5) //-> x=5
I believe this example is more barebones and easier to understand then @dowomenfart.
.child {
display: inline-block;
margin: 0 1em;
flex-grow: 1;
width: calc(25% - 2em);
}
This accomplishes the same width calculations while cutting straight to the meat. The math is way easier and em
is the new standard due to its scalability and mobile-friendliness.
got the below error
PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> npm install vue npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY npm ERR! errno UNABLE_TO_GET_ISSUER_CERT_LOCALLY npm ERR! request to https://registry.npmjs.org/vue failed, reason: unable to get local issuer certificate
npm ERR! A complete log of this run can be found in: npm ERR!
C:\Users\chpr\AppData\Roaming\npm-cache_logs\2020-07-29T03_22_40_225Z-debug.log PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> npm ERR!
C:\Users\chpr\AppData\Roaming\npm-cache_logs\2020-07-29T03_22_40_225Z-debug.log
Below command solved the issue:
npm config set strict-ssl false
Oh that's easy, just use extraData
You see the way extra data works behind the scenes is the FlatList or the VirtualisedList just checks wether that object has changed via a normal onComponentWillReceiveProps
method.
So all you have to do is make sure you give something that changes to the extraData
.
Here's what I do:
I'm using immutable.js so all I do is I pass a Map (immutable object) that contains whatever I want to watch.
<FlatList
data={this.state.calendarMonths}
extraData={Map({
foo: this.props.foo,
bar: this.props.bar
})}
renderItem={({ item })=>((
<CustomComponentRow
item={item}
foo={this.props.foo}
bar={this.props.bar}
/>
))}
/>
In that way, when this.props.foo
or this.props.bar
change, our CustomComponentRow
will update, because the immutable object will be a different one than the previous.
To add ...
in the end of the second line, saving 1 line if text is short:
android:maxLines="2"
android:ellipsize="end"
From you main machine, start -> search -> "remote desktop connection" -> click on "remote desktop connection" -> Click "Options" Beside to "Connect Button" -> Display Tab - > Then increase Display Configuriton Size. If this will not work, try the same thing by closing remote desktop. But this will give you solution.
Avoid async void
. Have your methods return Task
instead of void
. Then you can await
them.
Like this:
private async Task RequestToSendOutputReport(List<byte[]> byteArrays)
{
foreach (byte[] b in byteArrays)
{
while (condition)
{
// we'll typically execute this code many times until the condition is no longer met
Task t = SendOutputReportViaInterruptTransfer();
await t;
}
// read some data from device; we need to wait for this to return
await RequestToGetInputReport();
}
}
private async Task RequestToGetInputReport()
{
// lots of code prior to this
int bytesRead = await GetInputReportViaInterruptTransfer();
}
Yes - it means you're using \n
as the line break instead of \r\n
. Notepad only understands the latter.
(Note that Environment.NewLine
suggested by others is fine if you want the platform default - but if you're serving from Mono and definitely want \r\n
, you should specify it explicitly.)
demo
branch into master
git fetch --all
demo
branch on localgit pull origin demo
master
branch. This branch will be completely changed with the code on demo
branchgit checkout master
master
branch and run this command.git reset --hard origin/demo
reset
means you will be resetting current branch
--hard
is a flag that means it will be reset without raising any merge conflict
origin/demo
will be the branch that will be considered to be the code that will forcefully overwrite current master
branch
The output of the above command will show you your last commit message on origin/demo
or demo
branch
Then, in the end, force push the code on the master
branch to your remote repo.
git push --force
here is the doc to read a csv : http://www.mathworks.com/access/helpdesk/help/techdoc/ref/csvread.html and to write : http://www.mathworks.com/access/helpdesk/help/techdoc/ref/csvwrite.html
EDIT
An example that works :
file.csv :
1,50,4.1 2,49,4.2 3,30,4.1 4,71,4.9 5,51,4.5 6,61,4.1
the code :
File = csvread('file.csv') [m,n] = size(File) index=1 temp=0 for i = 1:m if (File(i,2)>=50) temp = temp + 1 end end Matrix = zeros(temp, 3) for j = 1:m if (File(j,2)>=50) Matrix(index,1) = File(j,1) Matrix(index,2) = File(j,2) Matrix(index,3) = File(j,3) index = index + 1 end end csvwrite('outputFile.csv',Matrix)
and the output file result :
1,50,4.1 4,71,4.9 5,51,4.5 6,61,4.1
This isn't probably the best solution but it works! We can read the CSV file, control the distance of each row and save it in a new file.
Hope it will help!
In Bash using pseudo-device files for TCP/UDP connections is straight forward. Here is the script:
#!/usr/bin/env bash
SERVER=example.com
PORT=80
</dev/tcp/$SERVER/$PORT
if [ "$?" -ne 0 ]; then
echo "Connection to $SERVER on port $PORT failed"
exit 1
else
echo "Connection to $SERVER on port $PORT succeeded"
exit 0
fi
Testing:
$ ./test.sh
Connection to example.com on port 80 succeeded
Here is one-liner (Bash syntax):
</dev/tcp/localhost/11211 && echo Port open. || echo Port closed.
Note that some servers can be firewall protected from SYN flood attacks, so you may experience a TCP connection timeout (~75secs). To workaround the timeout issue, try:
timeout 1 bash -c "</dev/tcp/stackoverflow.com/81" && echo Port open. || echo Port closed.
If you want to just untrack a file and not delete from local and remote repo then use this command:
git update-index --assume-unchanged file_name_with_path
In ES6, it is also possible to iterate over the values of an object using the for..of
loop. This doesn't work right out of the box for JavaScript objects, however, as you must define an @@iterator property on the object. This works as follows:
for..of
loop asks the "object to be iterated over" (let's call it obj1 for an iterator object. The loop iterates over obj1 by successively calling the next() method on the provided iterator object and using the returned value as the value for each iteration of the loop.Here is an example:
const obj1 = {
a: 5,
b: "hello",
[Symbol.iterator]: function() {
const thisObj = this;
let index = 0;
return {
next() {
let keys = Object.keys(thisObj);
return {
value: thisObj[keys[index++]],
done: (index > keys.length)
};
}
};
}
};
Now we can use the for..of
loop:
for (val of obj1) {
console.log(val);
} // 5 hello
So it is very easy to disable any button in react native
<TouchableOpacity disabled={true}>
<Text>
This is disabled button
</Text>
</TouchableOpacity>
disabled is a prop in react native and when you set its value to "true" it will disable your button
Happy Cooding
Another way to do it in Postgres would be to use the idx
function.
SELECT *
FROM comments
ORDER BY idx(array[1,3,2,4], comments.id)
Don't forget to create the idx
function first, as described here: http://wiki.postgresql.org/wiki/Array_Index
The keyboard shortcut cmd-t
opens a new tab, so you can pass this keystroke to OSA command as follows:
osascript -e 'tell application "System Events"' -e 'keystroke "t" using command down' -e 'end tell'
mysql> SHOW ENGINE INNODB STATUS;
But in my case only this way could help:
1. Make backup of current DB
2. Drop DB (not all tables, but DB)
3. Create DB (check that you still have previleges)
4. Restore DB from backup
$("#chkdwn2").change(function() {
if (this.checked) $("#dropdown").prop("disabled",'disabled');
})
This worked perfectly for me : sValue = sValue.trim().replaceAll("\\s+", " ");
What worked for me (in ubuntu):
sudo su
cd /etc/apache2/mods-enabled
ln ../mods-available/rewrite.load rewrite.load
Also, as already mentioned, make sure AllowOverride all
is set in the relevant section of /etc/apache2/sites-available/default
This is because the .pubxml.user contains required information to publish, and that file isn't (and shouldn't) be included in source control. To fix this VS bug, copy the information from the .pubxml.user file to the .pubxml file. The relevant properties are:
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
Put those in your .pubxml and you should be good to go.
Checkout https://mrin9.github.io/RapiPdf a custom element with plenty of customization and localization feature.
Disclaimer: I am the author of this package
for OSX, like the 10342 answers above made clear, you need to make sure that vim supports the clipboard feature, said the the one that comes pre-shipped with OSX does NOT support clipboard, and that if you run
brew install vim
it would work.
Except that running vi will still make you run the preshipped OSX version, not the one you installed from brew.
to get over this, I simply aliased my vim command to the brew version, not the OSX default one:
alias vim="/usr/local/Cellar/vim/8.0.1100_1/bin/vim"
and now i'm golden
Take a look on life cycle of Activity
Where
***onCreate()***
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
***onStart()***
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
And you can write your simple class to take a look when these methods call
public class TestActivity extends Activity {
/** Called when the activity is first created. */
private final static String TAG = "TestActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "On Create .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onDestroy()
*/
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "On Destroy .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "On Pause .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onRestart()
*/
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "On Restart .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "On Resume .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "On Start .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStop()
*/
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "On Stop .....");
}
}
Hope this will clear your confusion.
And take a look here for details.
Lifecycle Methods in Details is a very good example and demo application, which is a very good article to understand the life cycle.
I realize this is old; however, here would be how to do so using just the os module...
def purgedir(parent):
for root, dirs, files in os.walk(parent):
for item in files:
# Delete subordinate files
filespec = os.path.join(root, item)
if filespec.endswith('.bak'):
os.unlink(filespec)
for item in dirs:
# Recursively perform this operation for subordinate directories
purgedir(os.path.join(root, item))
From the documentation, you do it like:
<div class="row">
<div class="col-md-6">left</div>
<div class="col-md-push-6">content needs to be right aligned</div>
</div>
Quick summary:
import "math/bits"
const (
MaxUint uint = (1 << bits.UintSize) - 1
MaxInt int = (1 << bits.UintSize) / 2 - 1
MinInt int = (1 << bits.UintSize) / -2
)
Background:
As I presume you know, the uint
type is the same size as either uint32
or uint64
, depending on the platform you're on. Usually, one would use the unsized version of these only when there is no risk of coming close to the maximum value, as the version without a size specification can use the "native" type, depending on platform, which tends to be faster.
Note that it tends to be "faster" because using a non-native type sometimes requires additional math and bounds-checking to be performed by the processor, in order to emulate the larger or smaller integer. With that in mind, be aware that the performance of the processor (or compiler's optimised code) is almost always going to be better than adding your own bounds-checking code, so if there is any risk of it coming into play, it may make sense to simply use the fixed-size version, and let the optimised emulation handle any fallout from that.
With that having been said, there are still some situations where it is useful to know what you're working with.
The package "math/bits" contains the size of uint
, in bits. To determine the maximum value, shift 1
by that many bits, minus 1. ie: (1 << bits.UintSize) - 1
Note that when calculating the maximum value of uint
, you'll generally need to put it explicitly into a uint
(or larger) variable, otherwise the compiler may fail, as it will default to attempting to assign that calculation into a signed int
(where, as should be obvious, it would not fit), so:
const MaxUint uint = (1 << bits.UintSize) - 1
That's the direct answer to your question, but there are also a couple of related calculations you may be interested in.
According to the spec, uint
and int
are always the same size.
uint
either 32 or 64 bits
int
same size asuint
So we can also use this constant to determine the maximum value of int
, by taking that same answer and dividing by 2
then subtracting 1
. ie: (1 << bits.UintSize) / 2 - 1
And the minimum value of int
, by shifting 1
by that many bits and dividing the result by -2
. ie: (1 << bits.UintSize) / -2
In summary:
MaxUint: (1 << bits.UintSize) - 1
MaxInt: (1 << bits.UintSize) / 2 - 1
MinInt: (1 << bits.UintSize) / -2
full example (should be the same as below)
package main
import "fmt"
import "math"
import "math/bits"
func main() {
var mi32 int64 = math.MinInt32
var mi64 int64 = math.MinInt64
var i32 uint64 = math.MaxInt32
var ui32 uint64 = math.MaxUint32
var i64 uint64 = math.MaxInt64
var ui64 uint64 = math.MaxUint64
var ui uint64 = (1 << bits.UintSize) - 1
var i uint64 = (1 << bits.UintSize) / 2 - 1
var mi int64 = (1 << bits.UintSize) / -2
fmt.Printf(" MinInt32: %d\n", mi32)
fmt.Printf(" MaxInt32: %d\n", i32)
fmt.Printf("MaxUint32: %d\n", ui32)
fmt.Printf(" MinInt64: %d\n", mi64)
fmt.Printf(" MaxInt64: %d\n", i64)
fmt.Printf("MaxUint64: %d\n", ui64)
fmt.Printf(" MaxUint: %d\n", ui)
fmt.Printf(" MinInt: %d\n", mi)
fmt.Printf(" MaxInt: %d\n", i)
}
I'm using this to address the security implications noted in @CMS's answer.
// example 1: www.example.com/index.html#foo
// load correct subpage from URL hash if it exists
$(window).on('load', function () {
var hash = window.location.hash;
if (hash) {
hash = hash.replace('#',''); // strip the # at the beginning of the string
hash = hash.replace(/([^a-z0-9]+)/gi, '-'); // strip all non-alphanumeric characters
hash = '#' + hash; // hash now equals #foo with example 1
// do stuff with hash
$( 'ul' + hash + ':first' ).show();
// etc...
}
});
Assuming doc
is your instance of org.w3c.dom.Document
:
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
A solution with numpy for quick access to all indexes:
string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')
See http://jsfiddle.net/qP8DY/24/
You can add a class (such as "success-dialog" in my example) to div#success, either directly in your HTML, or in your JavaScript by adding to the dialogClass option, as I've done.
$('#success').dialog({
height: 50,
width: 350,
modal: true,
resizable: true,
dialogClass: 'no-close success-dialog'
});
Then just add the success-dialog class to your CSS rules as appropriate. To indicate an element with two (or more) classes applied to it, just write them all together, with no spaces in between. For example:
.ui-dialog.success-dialog {
font-family: Verdana,Arial,sans-serif;
font-size: .8em;
}
NB This answer is factually incorrect; as pointed out by a comment below, success() does return the original promise. I'll not change; and leave it to OP to edit.
The major difference between the 2 is that .then()
call returns a promise (resolved with a value returned from a callback) while .success()
is more traditional way of registering callbacks and doesn't return a promise.
Promise-based callbacks (.then()
) make it easy to chain promises (do a call, interpret results and then do another call, interpret results, do yet another call etc.).
The .success()
method is a streamlined, convenience method when you don't need to chain call nor work with the promise API (for example, in routing).
In short:
.then()
- full power of the promise API but slightly more verbose.success()
- doesn't return a promise but offeres slightly more convienient syntaxHere is another JQuery-based solution without any timers:
<script type="text/javascript">
function loadScript(url, onsuccess, onerror) {
$.get(url)
.done(function() {
// File/url exists
console.log("JS Loader: file exists, executing $.getScript "+url)
$.getScript(url, function() {
if (onsuccess) {
console.log("JS Loader: Ok, loaded. Calling onsuccess() for " + url);
onsuccess();
console.log("JS Loader: done with onsuccess() for " + url);
} else {
console.log("JS Loader: Ok, loaded, no onsuccess() callback " + url)
}
});
}).fail(function() {
// File/url does not exist
if (onerror) {
console.error("JS Loader: probably 404 not found. Not calling $.getScript. Calling onerror() for " + url);
onerror();
console.error("JS Loader: done with onerror() for " + url);
} else {
console.error("JS Loader: probably 404 not found. Not calling $.getScript. No onerror() callback " + url);
}
});
}
</script>
Thanks to: https://stackoverflow.com/a/14691735/1243926
Sample usage (original sample from JQuery getScript documentation):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getScript demo</title>
<style>
.block {
background-color: blue;
width: 150px;
height: 70px;
margin: 10px;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<button id="go">» Run</button>
<div class="block"></div>
<script>
function loadScript(url, onsuccess, onerror) {
$.get(url)
.done(function() {
// File/url exists
console.log("JS Loader: file exists, executing $.getScript "+url)
$.getScript(url, function() {
if (onsuccess) {
console.log("JS Loader: Ok, loaded. Calling onsuccess() for " + url);
onsuccess();
console.log("JS Loader: done with onsuccess() for " + url);
} else {
console.log("JS Loader: Ok, loaded, no onsuccess() callback " + url)
}
});
}).fail(function() {
// File/url does not exist
if (onerror) {
console.error("JS Loader: probably 404 not found. Not calling $.getScript. Calling onerror() for " + url);
onerror();
console.error("JS Loader: done with onerror() for " + url);
} else {
console.error("JS Loader: probably 404 not found. Not calling $.getScript. No onerror() callback " + url);
}
});
}
loadScript("https://raw.github.com/jquery/jquery-color/master/jquery.color.js", function() {
console.log("loaded jquery-color");
$( "#go" ).click(function() {
$( ".block" )
.animate({
backgroundColor: "rgb(255, 180, 180)"
}, 1000 )
.delay( 500 )
.animate({
backgroundColor: "olive"
}, 1000 )
.delay( 500 )
.animate({
backgroundColor: "#00f"
}, 1000 );
});
}, function() { console.error("Cannot load jquery-color"); });
</script>
</body>
</html>
I defined a median function for a list of numbers as
def median(numbers):
return (sorted(numbers)[int(round((len(numbers) - 1) / 2.0))] + sorted(numbers)[int(round((len(numbers) - 1) // 2.0))]) / 2.0
I think you want to write text in an oval or circle? why not this one?
<span style="border-radius:50%; border:solid black 1px;padding:5px">Hello</span>
_x000D_
In current versions of Matplotlib, you can do axis.set_xticklabels(labels, fontsize='small')
.
Please use the following syntax to remove the border of text box and remove the highlighted border of browser style.
input {
background-color:transparent;
border: 0px solid;
height:30px;
width:260px;
}
input:focus {
outline:none;
}
You can use JQuery Ajax and POST method:
var obj;
$(document).ready(function(){
$("#button1").click(function(){
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: "addperson.php",
type: "POST",
async: false,
data: {
username: username,
password: password
}
})
.done (function(data, textStatus, jqXHR) {
obj = JSON.parse(data);
})
.fail (function(jqXHR, textStatus, errorThrown) {
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) {
});
});
});
To take a response back from the php script JSON parse the the respone in .done()
method.
Here is the php script you can modify to your needs:
<?php
$username1 = isset($_POST["username"]) ? $_POST["username"] : '';
$password1 = isset($_POST["password"]) ? $_POST["password"] : '';
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";
;
if ($conn->query($sql) === TRUE) {
echo json_encode(array('success' => 1));
} else{
echo json_encode(array('success' => 0));
}
$conn->close();
?>
Recommend you use FREQUENCY
rather than using COUNTIF
.
In your front sheet; enter 01/04/2014
into E5
, 01/05/2014
into E6
etc.
Select the range of adjacent cells you want to populate. Enter:
=FREQUENCY(2013!!$A$2:$A$50,'2013 Metrics'!E5:EN)
(where N is the final row reference in your range)
Hit Ctrl + Shift + Enter
If both projects are contained within the same solution, it will be more apropiate if you add the reference for the project you need, not its compiled dll.
This should work
background: url("youimage.png") no-repeat center center fixed;
-webkit-background-size: 100% auto;
-moz-background-size: 100% auto;
-o-background-size: 100% auto;
background-size: 100% auto;
A more efficient method, that uses integer math rather than strings/varchars, that will result in an int type rather than a string type is:
SELECT YYYYMM = (YEAR(GETDATE()) * 100) + MONTH(GETDATE())
Adds two zeros to the right side of the year and then adds the month to the added two zeros.
My solution for making a responsive navbar ( position: 'relative' when not scrolling and fixed when scrolling and not at the top of the page)
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll(event) {
if (window.scrollY === 0 && this.state.scrolling === true) {
this.setState({scrolling: false});
}
else if (window.scrollY !== 0 && this.state.scrolling !== true) {
this.setState({scrolling: true});
}
}
<Navbar
style={{color: '#06DCD6', borderWidth: 0, position: this.state.scrolling ? 'fixed' : 'relative', top: 0, width: '100vw', zIndex: 1}}
>
No performance issues for me.
I want to share something that blocked us for a couple of days: the fileprovider code MUST be inserted between the application tags, not after it. It may be trivial, but it's never specified, and I thought that I could have helped someone! (thanks again to piolo94)
In the question above the right answer would be to use Mock
, or to be more precise create_autospec
(because it will add spec to the mock methods of the class you are mocking), the defined spec
on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some
from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch
class MyClass:
@staticmethod
def method(foo, bar):
print(foo)
def something(some_class: MyClass):
arg = 1
# Would fail becuase of wrong parameters passed to methd.
return some_class.method(arg)
def second(some_class: MyClass):
arg = 1
return some_class.unexisted_method(arg)
class TestSomethingTestCase(TestCase):
def test_something_with_autospec(self):
mock = create_autospec(MyClass)
mock.method.return_value = True
# Fails because of signature misuse.
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_something(self):
mock = Mock() # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
mock.method.return_value = True
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
class TestSecondTestCase(TestCase):
def test_second_with_autospec(self):
mock = Mock(spec=MyClass)
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second(self):
mock = Mock()
mock.unexisted_method.return_value = True
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
The test cases with defined spec used fail because methods called from something
and second
functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock
will display.
As a side note there is one more option: use patch.object to mock just the class method which is called with.
The good use cases for patch would be the case when the class is used as inner part of function:
def something():
arg = 1
return MyClass.method(arg)
Then you will want to use patch as a decorator to mock the MyClass.
Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):
Sub Module for Connecting to MS SQL with Remote Host & Username/Password
Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
Yes it is true.
If you create two instance of your class
Test t1 = new Test();
Test t2 = new Test();
Then t1.foo and t2.foo both synchronize on the same static object and hence block each other.
directoryName = "Photographs"
filePath = os.path.abspath(directoryName)
filePathWithSlash = filePath + "\\"
for counter, filename in enumerate(os.listdir(directoryName)):
filenameWithPath = os.path.join(filePathWithSlash, filename)
os.rename(filenameWithPath, filenameWithPath.replace(filename,"DSC_" + \
str(counter).zfill(4) + ".jpg" ))
# e.g. filename = "photo1.jpg", directory = "c:\users\Photographs"
# The string.replace call swaps in the new filename into
# the current filename within the filenameWitPath string. Which
# is then used by os.rename to rename the file in place, using the
# current (unmodified) filenameWithPath.
# os.listdir delivers the filename(s) from the directory
# however in attempting to "rename" the file using os
# a specific location of the file to be renamed is required.
# this code is from Windows
Is there something that prevents you from merging all revisions on trunk since the last merge?
svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc
should work just fine. At least if you want to merge all changes on trunk to your branch.
4 spaces do the trick even inside definition list:
Endpoint
: `/listAgencies`
Method
: `GET`
Arguments
: * `level` - bla-bla.
* `withDisabled` - should we include disabled `AGENT`s.
* `userId` - bla-bla.
I am documenting API using BitBucket Wiki and Markdown proprietary extension for definition list is most pleasing (MD's table syntax is awful, imaging multiline and embedding requirements...).
After some time with Google I asked on the ask ubuntu chat room.
A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:
grep -P "(^|\s)abc(\s|$)"
gives the result I was looking for. -P is an experimental implementation of perl regexps.
grepping for abc
and then using filters like grep -v '@abc'
(this is far from perfect...) should also work, but my patch does something similar.
I think you are trying to check whether the array is empty or not.You can do like this :
@if(!$result->isEmpty())
// $result is not empty
@else
// $result is empty
@endif
Reference isEmpty()
Check Bash Flatten Folder script that converts folder hierarchy to a single folder
For the record: When you add an import, you are also indicating your dependencies.
You could see quickly what are the dependencies of files (excluding classes of the same namespace).
You can use @@trancount
in MSSQL
From the documentation:
Returns the number of BEGIN TRANSACTION statements that have occurred on the current connection.
Does this work?
float flt = 145.664454;
Double dbl = 0.0;
dbl += flt;