If you are using vs 2010 then you can get it in
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools
You'll probably want to get several random numbers, and may want to be able to specify a different range for each one, so you should define a function. In my example, I generate numbers from 25 through 30 with call:rand 25 30
. And the result is in RAND_NUM
after that function exits.
@echo off & setlocal EnableDelayedExpansion
for /L %%a in (1 1 10) do (
call:rand 25 30
echo !RAND_NUM!
)
goto:EOF
REM The script ends at the above goto:EOF. The following are functions.
REM rand()
REM Input: %1 is min, %2 is max.
REM Output: RAND_NUM is set to a random number from min through max.
:rand
SET /A RAND_NUM=%RANDOM% * (%2 - %1 + 1) / 32768 + %1
goto:EOF
You might looking for the placeholder
attribute which will display a grey text in the input field while empty.
From Mozilla Developer Network:
A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored.
However as it's a fairly 'new' tag (from the HTML5 specification afaik) you might want to to browser testing to make sure your target audience is fine with this solution.
(If not tell tell them to upgrade browser 'cause this tag works like a charm ;o) )
And finally a mini-fiddle to see it directly in action: http://jsfiddle.net/LnU9t/
Edit: Here is a plain jQuery solution which will also clear the input field if an escape keystroke is detected: http://jsfiddle.net/3GLwE/
I had the same issue, multiple data type values in single column, package load only numeric values. Remains all it updated as null.
Solution
To fix this changing the excel data type is one of the solution. In Excel Copy the column data and paste in different file. Delete that column and insert new column as Text datatype and paste that copied data in new column.
Now in ssis package delete and recreate the Excel source and destination table change the column data type as varchar.
This will work.
You dont need both jTDS and JDBC in your classpath. Any one is required. Here you need only sqljdbc.jar
.
Also, I would suggest to place sqljdbc.jar
at physical location to /WEB-INF/lib
directory of your project rather than adding it in the Classpath via IDE. Then Tomcat takes care the rest. And also try restarting Tomcat.
You can download Jar from : www.java2s.com/Code/JarDownload/sqlserverjdbc/sqlserverjdbc.jar.zip
EDIT:
As you are supplying Username and Password when connecting,
You need only jdbc:sqlserver://localhost:1433;databaseName=test
, Skip integratedSecurity
attribute.
In [16]: df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))
In [17]: df
Out[17]:
A B
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
In [18]: df.dtypes
Out[18]:
A int64
B int64
dtype: object
Convert a series
In [19]: df['A'].apply(str)
Out[19]:
0 0
1 2
2 4
3 6
4 8
Name: A, dtype: object
In [20]: df['A'].apply(str)[0]
Out[20]: '0'
Don't forget to assign the result back:
df['A'] = df['A'].apply(str)
Convert the whole frame
In [21]: df.applymap(str)
Out[21]:
A B
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
In [22]: df.applymap(str).iloc[0,0]
Out[22]: '0'
df = df.applymap(str)
I had this problem and this is the best solution without any external or additional script libraries: In Javascript tags or file create this function: We assume here that canvas is your canvas:
function download(){
var download = document.getElementById("download");
var image = document.getElementById("canvas").toDataURL("image/png")
.replace("image/png", "image/octet-stream");
download.setAttribute("href", image);
}
In the body part of your HTML specify the button:
<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>
This is working and download link looks like a button. Tested in Firefox and Chrome.
If you use read_excel()
on a file opened using the function open()
, make sure to add rb
to the open function to avoid encoding errors
SHOW KEYS FROM tablename WHERE Key_name='unique key name'
you can find if there exists an unique key in the table
Following should work
$d = strtotime("+1 months",strtotime("2015-05-25"));
echo date("Y-m-d",$d); // This will print **2015-06-25**
This can be done if you are using Mockito2, with the new incubating feature which supports mocking of final classes & methods.
Key points to note:
1. Create a simple file with the name “org.mockito.plugins.MockMaker” and place it in a folder named “mockito-extensions”. This folder should be made available on the classpath.
2. The content of the file created above should be a single line as given below:
mock-maker-inline
The above two steps are required in order to activate the mockito extension mechanism and use this opt-in feature.
Sample classes are as follows:-
FinalClass.java
public final class FinalClass {
public final String hello(){
System.out.println("Final class says Hello!!!");
return "0";
}
}
Foo.java
public class Foo {
public String executeFinal(FinalClass finalClass){
return finalClass.hello();
}
}
FooTest.java
public class FooTest {
@Test
public void testFinalClass(){
// Instantiate the class under test.
Foo foo = new Foo();
// Instantiate the external dependency
FinalClass realFinalClass = new FinalClass();
// Create mock object for the final class.
FinalClass mockedFinalClass = mock(FinalClass.class);
// Provide stub for mocked object.
when(mockedFinalClass.hello()).thenReturn("1");
// assert
assertEquals("0", foo.executeFinal(realFinalClass));
assertEquals("1", foo.executeFinal(mockedFinalClass));
}
}
Hope it helps.
Complete article present here mocking-the-unmockable.
old question, new verb in tidyverse:
library(tidyr) # version >= 0.8.0
df <- data.frame(var1=c('a', 'b', 'c'), var2=c('d', 'e', 'f'), freq=1:3)
df %>%
uncount(freq)
var1 var2
1 a d
2 b e
2.1 b e
3 c f
3.1 c f
3.2 c f
Because LINQ
can do everything...:
string test = "key1=value1&key2=value2&key3=value3";
var count = test.Where(x => x == '&').Count();
Or if you like, you can use the Count
overload that takes a predicate :
var count = test.Count(x => x == '&');
I updated Xcode to v8 and the error was resolved.
I have written a generic caching func()
which will cache any variable easily and very readable format.
Caching function:
function calculateSomethingMaybe(args){
return args;
}
function caching(fn){
const cache = {};
return function(){
const string = arguments[0];
if(!cache[string]){
const result = fn.apply(this, arguments);
cache[string] = result;
return result;
}
return cache[string];
}
}
const letsCache = caching(calculateSomethingMaybe);
console.log(letsCache('a book'), letsCache('a pen'), letsCache('a book'));
If you are trying to configure this on 64bit, you have to do your DCOMconfig configuration (see other answers above) in:
C:\WINDOWS\SysWOW64>mmc comexp.msc /32
according to Setting Process-Wide Security Using DCOMCNFG.
After this, I was able to configure this for IIS_IUSRS
without administrator privileges.
This is the accepted answer written in a decorative way:
Toolkit.getDefaultToolkit()
.getSystemClipboard()
.setContents(
new StringSelection(txtMySQLScript.getText()),
null
);
In Eclipse Photon navigate to Windows > Preferences > Maven > User Settings > User Setting
For "User settings" Browse to the settings.xml of the maven. ex. in my case maven it is located on the path C:\Program Files\Apache Software Distribution\apache-maven-3.5.4\conf\Settings.xml
Depending on the Settings.xml the Local Repository gets automatically configured to the specified location.
Long time since I've done Assembly programming, but this link might be useful...
The processor has a collection of registers which are used to store data. Some of these are direct values while others are pointing to an area within RAM. Registers do tend to be used for certain specific actions and every operand in assembly will require a certain amount of data in specific registers.
The stack pointer is mostly used when you're calling other procedures. With modern compilers, a bunch of data will be dumped first on the stack, followed by the return address so the system will know where to return once it's told to return. The stack pointer will point at the next location where new data can be pushed to the stack, where it will stay until it's popped back again.
Base registers or segment registers just point to the address space of a large amount of data. Combined with a second regiser, the Base pointer will divide the memory in huge blocks while the second register will point at an item within this block. Base pointers therefor point to the base of blocks of data.
Do keep in mind that Assembly is very CPU specific. The page I've linked to provides information about different types of CPU's.
you need to use backslash before ". like \"
From the doc here you can see that
A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.
and " (double quote) is a escacpe sequence
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence
She said "Hello!" to me.
you would write
System.out.println("She said \"Hello!\" to me.");
It should be MM
for months. You are asking for minutes.
DateTime.Now.ToString("dd/MM/yyyy");
See Custom Date and Time Format Strings on MSDN for details.
If your textfile manipulation usually is one-time, possibly done on the shell-prompt, you will not get anything better from python.
On the other hand, if you usually have to do the same (or similar) task over and over, and you have to write your scripts for doing that, then python is great - and you can easily create your own libraries (you can do that with shell scripts too, but it's more cumbersome).
A very simple example to get a feeling.
import popen2
stdout_text, stdin_text=popen2.popen2("your-shell-command-here")
for line in stdout_text:
if line.startswith("#"):
pass
else
jobID=int(line.split(",")[0].split()[1].lstrip("<").rstrip(">"))
# do something with jobID
Check also sys and getopt module, they are the first you will need.
I done it, below code is working for me....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
Button newPage = (Button)v.findViewById(R.id.click);
newPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
});
return v;
}
and Please make sure that your destination activity should be register in Manifest.xml file,
but in my case all tabs are not shown in HomeActivity, is any solution for that ?
I am trying to do something similar to this. As commented above, I think you would want to build a new image with a custom Dockerfile (using the image you pulled as a base image), ADD
your certificate, then RUN update-ca-certificates
. This way you will have a consistent state each time you start a container from this new image.
# Dockerfile
FROM some-base-image:0.1
ADD you_certificate.crt:/container/cert/path
RUN update-ca-certificates
Let's say a docker build
against that Dockerfile produced IMAGE_ID. On the next docker run -d [any other options] IMAGE_ID
, the container started by that command will have your certificate info. Simple and reproducible.
ReferenceError: Can't find variable: require.
You have installed "npm", you can run as normal the script to a "localhost" "127.0.0.1".
When you use the http.clientRequest() with "options" in a "npm" you need to install "RequireJS" inside of the module.
A module is any file or directory in the node_modules directory that can be loaded by the Node. Install "RequiereJS" for to make work the http.clientRequest(options).
here is the solution
Put your html and css in your /assets/ folder, then load the html file like so:
WebView wv = new WebView(this);
wv.loadUrl("file:///android_asset/yourHtml.html");
then in your html you can reference your css in the usual way
<link rel="stylesheet" type="text/css" href="main.css" />
It is easy to configure it using your system local zone, Just in your application.rb add this
config.time_zone = Time.now.zone
Then, rails should show you timestamps in your localtime or you can use something like this instruction to get the localtime
Post.created_at.localtime
If you get to the point where all the mentioned solutions don't work (as it got for me), do this:
Like this, in your HTML
<div class="table-header-class">
<table>
<thead>
<tr>
<th>Ava</th>
<th>Alexis</th>
<th>Mcclure</th>
</tr>
</thead>
</table>
</div>
<div class="table-content-class">
<table>
<tbody>
<tr>
<td>I am the boss</td>
<td>No, da-da is not the boss!</td>
<td>Alexis, I am the boss, right?</td>
</tr>
</tbody>
</table>
</div>
Then style the second table's parent to allow vertical scroll, in your CSS
.table-content-class {
overflow-y: scroll; // use auto; or scroll; to allow vertical scrolling;
overflow-x: hidden; // disable horizontal scroll
}
I wanted a simple function that took a URL as an input and returned a map of the query params. If I were to improve this function, I would support the standard for array data in the URL, and or nested variables.
This should work back and for with the jQuery.param( qparams ) function.
function getQueryParams(url){
var qparams = {},
parts = (url||'').split('?'),
qparts, qpart,
i=0;
if(parts.length <= 1 ){
return qparams;
}else{
qparts = parts[1].split('&');
for(i in qparts){
qpart = qparts[i].split('=');
qparams[decodeURIComponent(qpart[0])] =
decodeURIComponent(qpart[1] || '');
}
}
return qparams;
};
As a workaround, you could store a bundle with the data you want to maintain in the Intent you use to start activity A.
Intent intent = new Intent(this, ActivityA.class);
intent.putExtra("bundle", theBundledData);
startActivity(intent);
Activity A would have to pass this back to Activity B. You would retrieve the intent in Activity B's onCreate method.
Intent intent = getIntent();
Bundle intentBundle;
if (intent != null)
intentBundle = intent.getBundleExtra("bundle");
// Do something with the data.
Another idea is to create a repository class to store activity state and have each of your activities reference that class (possible using a singleton structure.) Though, doing so is probably more trouble than it's worth.
Take a look at the articles:
1) PdftoImage-Convert PDF to Image by using PdfRenderer library, direct link to source code
2) Java: Generating PDF and Previewing it as an Image – iText and PDF Renderer
The answer above (by Janusz) is quite correct, but I personnally don't feel 100% confortable with RelativeLayouts, so I prefer to introduce a 'filler', empty TextView, like this:
<!-- filler -->
<TextView android:layout_height="0dip"
android:layout_width="fill_parent"
android:layout_weight="1" />
before the element that should be at the bottom of the screen.
This is a simple solution for those wishing to simply remove the right-click "save" option from the html5 videos
$(document).ready(function(){
$('#videoElementID').bind('contextmenu',function() { return false; });
});
Another tool is tcpmon. This is a java open-source tool to monitor a TCP connection. It's not directly a test server. It is placed in-between a client and a server but allow to see what is going through the "tube" and also to change what is going through.
Arrays are special objects in java, they have a simple attribute named length
which is final
.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
10.7. Array Members
The members of an array type are all of the following:
- The
public
final
fieldlength
, which contains the number of components of the array.length
may be positive or zero.The
public
methodclone
, which overrides the method of the same name in classObject
and throws no checked exceptions. The return type of theclone
method of an array typeT[]
isT[]
.A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
- All the members inherited from class
Object
; the only method ofObject
that is not inherited is itsclone
method.
Resources:
First install the RJSONIO and RCurl package:
install.packages("RJSONIO")_x000D_
install.packages("(RCurl")
_x000D_
Try below code using RJSONIO in console
library(RJSONIO)_x000D_
library(RCurl)_x000D_
json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")_x000D_
json_file2 = RJSONIO::fromJSON(json_file)_x000D_
head(json_file2)
_x000D_
To call the method, you need to qualify function with self.
. In addition to that, if you want to pass a filename, add a filename
parameter (or other name you want).
class MyHandler(FileSystemEventHandler):
def on_any_event(self, event):
srcpath = event.src_path
print (srcpath, 'has been ',event.event_type)
print (datetime.datetime.now())
filename = srcpath[12:]
self.dropbox_fn(filename) # <----
def dropbox_fn(self, filename): # <-----
print('In dropbox_fn:', filename)
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
I am Write this code in xml file ...
<Button
android:id="@+id/btn_register"
android:layout_margin="1dp"
android:layout_marginLeft="3dp"
android:layout_marginTop="10dp"
android:layout_weight="2"
android:onClick="register"
android:text="Register"
android:textColor="#000000"/>
And write this code in fragment...
public void register(View view) {
}
Dictionaries are unordered by definition, What would be the main reason for ordering by key? A list of tuples created by the sort method can be used for whatever the need may have been, but changing the list of tuples back into a dictionary will return a random order
>>> myDic
{10: 'b', 3: 'a', 5: 'c'}
>>> sorted(myDic.items())
[(3, 'a'), (5, 'c'), (10, 'b')]
>>> print(dict(myDic.items()))
{10: 'b', 3: 'a', 5: 'c'}
Setting readonly
on a widget only makes the input in the browser read-only. Adding a clean_sku
which returns instance.sku
ensures the field value will not change on form level.
def clean_sku(self):
if self.instance:
return self.instance.sku
else:
return self.fields['sku']
This way you can use model's (unmodified save) and avoid getting the field required error.
The dispatcher-servlet.xml
file contains all of your configuration for Spring MVC
. So in it you will find beans such as ViewHandlerResolvers
, ConverterFactories
, Interceptors
and so forth. All of these beans are part of Spring MVC
which is a framework that structures how you handle web requests, providing useful features such as databinding, view resolution and request mapping.
The application-context.xml
can optionally be included when using Spring MVC
or any other framework for that matter. This gives you a container that may be used to configure other types of spring beans that provide support for things like data persistence. Basically, in this configuration file is where you pull in all of the other goodies Spring offers.
These configuration files are configured in the web.xml file as shown:
Dispatcher Config
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Application Config
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/application-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
To configure controllers, annotate them with @Controller
then include the following in the dispatcher-context.xml
file:
<mvc:annotation-driven/>
<context:component-scan base-package="package.with.controllers.**" />
In Font Awesome 5 it can be done using pure CSS as in some of the above answers with some modifications.
ul {
list-style-type: none;
}
li:before {
position: absolute;
font-family: 'Font Awesome 5 free';
/* Use the Name of the Font Awesome free font, e.g.:
- 'Font Awesome 5 Free' for Regular and Solid symbols;
- 'Font Awesome 5 Brand' for Brands symbols.
- 'Font Awesome 5 Pro' for Regular and Solid symbols (Professional License);
*/
content: "\f1fc"; /* Unicode value of the icon to use: */
font-weight: 900; /* This is important, change the value according to the font family name
used above. See the link below */
color: red;
}
Without the correct font-weight, it will only show a blank square.
https://fontawesome.com/how-to-use/on-the-web/advanced/css-pseudo-elements#define
A better solution would be you use in style css, the command to break lines. Works in older versions of browsers.
p {
word-wrap: break-word;
}
Every answer uses .next()
or uses .beforeFirst()
and then .next()
. But why not this:
result.first();
So You just set the pointer to the first record and go from there. It's available since java 1.2 and I just wanted to mention this for anyone whose ResultSet
exists of one specific record.
Using sn.exe utility:
sn -T YourAssembly.dll
or loading the assembly in Reflector.
class.method
should work.
class SomeClass:
@classmethod
def some_class_method(cls):
pass
@staticmethod
def some_static_method():
pass
SomeClass.some_class_method()
SomeClass.some_static_method()
For anyone else wondering how to achieve this, here is my extended EditText
class EditTextNumeric
.
.setMaxLength(int)
- sets maximum number of digits
.setMaxValue(int)
- limit maximum integer value
.setMin(int)
- limit minimum integer value
.getValue()
- get integer value
import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.widget.EditText;
public class EditTextNumeric extends EditText {
protected int max_value = Integer.MAX_VALUE;
protected int min_value = Integer.MIN_VALUE;
// constructor
public EditTextNumeric(Context context) {
super(context);
this.setInputType(InputType.TYPE_CLASS_NUMBER);
}
// checks whether the limits are set and corrects them if not within limits
@Override
protected void onTextChanged(CharSequence text, int start, int before, int after) {
if (max_value != Integer.MAX_VALUE) {
try {
if (Integer.parseInt(this.getText().toString()) > max_value) {
// change value and keep cursor position
int selection = this.getSelectionStart();
this.setText(String.valueOf(max_value));
if (selection >= this.getText().toString().length()) {
selection = this.getText().toString().length();
}
this.setSelection(selection);
}
} catch (NumberFormatException exception) {
super.onTextChanged(text, start, before, after);
}
}
if (min_value != Integer.MIN_VALUE) {
try {
if (Integer.parseInt(this.getText().toString()) < min_value) {
// change value and keep cursor position
int selection = this.getSelectionStart();
this.setText(String.valueOf(min_value));
if (selection >= this.getText().toString().length()) {
selection = this.getText().toString().length();
}
this.setSelection(selection);
}
} catch (NumberFormatException exception) {
super.onTextChanged(text, start, before, after);
}
}
super.onTextChanged(text, start, before, after);
}
// set the max number of digits the user can enter
public void setMaxLength(int length) {
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(length);
this.setFilters(FilterArray);
}
// set the maximum integer value the user can enter.
// if exeeded, input value will become equal to the set limit
public void setMaxValue(int value) {
max_value = value;
}
// set the minimum integer value the user can enter.
// if entered value is inferior, input value will become equal to the set limit
public void setMinValue(int value) {
min_value = value;
}
// returns integer value or 0 if errorous value
public int getValue() {
try {
return Integer.parseInt(this.getText().toString());
} catch (NumberFormatException exception) {
return 0;
}
}
}
Example usage:
final EditTextNumeric input = new EditTextNumeric(this);
input.setMaxLength(5);
input.setMaxValue(total_pages);
input.setMinValue(1);
All other methods and attributes that apply to EditText
, of course work too.
You could consider using PDFObject by Philip Hutchison.
Alternatively, if you're looking for a non-Javascript solution, you could use markup like this:
<object data="myfile.pdf" type="application/pdf" width="100%" height="100%">
<p>Alternative text - include a link <a href="myfile.pdf">to the PDF!</a></p>
</object>
For anyone that just wants a COUNT of the connected clients I believe this will do it:
io.sockets.manager.server.connections
IEnumerable<Control> Ctrls = from Control ctrl in Me.Controls where ctrl is TextBox | ctrl is GroupBox select ctr;
Lambda Expressions
IEnumerable<Control> Ctrls = Me.Controls.Cast<Control>().Where(c => c is Button | c is GroupBox);
Try
sc query state= all
for a list of services and whether they are running or not.
Super Easy Way is
$('.CheckBxMSG').each(function () {
var ChkBxMsgId;
ChkBxMsgId = $(this).attr('id');
alert(ChkBxMsgId);
});
Tell me if this helps
You can do some pretty neat stuff once you understand that you can play with inheritance with this. However first let's understand something from this doc on background:
With CSS3, you can apply multiple backgrounds to elements. These are layered atop one another with the first background you provide on top and the last background listed in the back. Only the last background can include a background color.
So when one do:
background: red;
He is setting the background-color to red because red is the last value listed.
When one do:
background: linear-gradient(to right, grey 50%, yellow 2%) red;
Red is the background color once again BUT you will see a gradient.
.box{_x000D_
border-radius: 50%;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
background: linear-gradient(to right, grey 50%, yellow 2%) red;_x000D_
}_x000D_
_x000D_
.box::before{_x000D_
content: "";_x000D_
display: block;_x000D_
margin-left: 50%;_x000D_
height: 50%;_x000D_
border-radius: 0 100% 100% 0 / 50%;_x000D_
transform: translateX(70px) translateY(-26px) rotate(325deg);_x000D_
background: inherit;_x000D_
}
_x000D_
<div class="box">_x000D_
_x000D_
</div>
_x000D_
Now the same thing with background-color:
.box{_x000D_
border-radius: 50%;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
background: linear-gradient(to right, grey 50%, yellow 2%) red;_x000D_
}_x000D_
_x000D_
.box::before{_x000D_
content: "";_x000D_
display: block;_x000D_
margin-left: 50%;_x000D_
height: 50%;_x000D_
border-radius: 0 100% 100% 0 / 50%;_x000D_
transform: translateX(70px) translateY(-26px) rotate(325deg);_x000D_
background-color: inherit;_x000D_
}
_x000D_
<div class="box">_x000D_
_x000D_
</div>
_x000D_
The reason this happens is because when we are doing this :
background: linear-gradient(to right, grey 50%, yellow 2%) #red;
The last number sets the background-color.
Then in the before we are inheriting from background (then we get the gradient) or background color, then we get red.
I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.
The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)
From: http://technet.microsoft.com/en-us/library/ee681792.aspx:
"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."
Edit:
Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE
returned.
If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week
which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll
.
Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206
I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.
Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.
All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.
Here is the best solution for this. (ANGULAR All Version)
Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.
I have provided solution for this kind of similar question. You can find the full solution from here
export class CarComponent implements OnInit {
private _defaultCar: car = {
// default isCar is true
isCar: true,
// default wheels will be 4
wheels: 4
};
@Input() newCar: car = {};
constructor() {}
ngOnInit(): void {
// this will concate both the objects and the object declared later (ie.. ...this.newCar )
// will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT
this.newCar = { ...this._defaultCar, ...this.newCar };
// console.log(this.newCar);
}
}
To expand on Ryan's answer, when you are declaring variables (using Dim) you can cheat a little bit by using the predictive text feature in the VBE, as in the image below.
If it shows up in that list, then you can assign an object of that type to a variable. So not just a Worksheet, as Ryan pointed out, but also a Chart, Range, Workbook, Series and on and on.
You set that variable equal to the object you want to manipulate and then you can call methods, pass it to functions, etc, just like Ryan pointed out for this example. You might run into a couple snags when it comes to collections vs objects (Chart or Charts, Range or Ranges, etc) but with trial and error you'll get it for sure.
You're trying to call an instance method on the class. To call an instance method on a class you must create an instance on which to call the method. If you want to call the method on non-instances add the static keyword. For example
class Example {
public static string NonInstanceMethod() {
return "static";
}
public string InstanceMethod() {
return "non-static";
}
}
static void SomeMethod() {
Console.WriteLine(Example.NonInstanceMethod());
Console.WriteLine(Example.InstanceMethod()); // Does not compile
Example v1 = new Example();
Console.WriteLine(v1.InstanceMethod());
}
another way which can return the list of matching strings is
sample = "alexis has the control"
matched_strings = filter(sample.endswith, ["trol", "ol", "troll"])
print matched_strings
['trol', 'ol']
I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).
A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.
Do like this:
create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;
Yet another answer...but I usually find myself in a case, when I need to load data simultaneously and put it into variables, like:
var cats = new List<Cat>();
var dog = new Dog();
var loadDataTasks = new Task[]
{
Task.Run(async () => cats = await LoadCatsAsync()),
Task.Run(async () => dog = await LoadDogAsync())
};
try
{
await Task.WhenAll(loadDataTasks);
}
catch (Exception ex)
{
// handle exception
}
I see the other one is closed. So basically here's the rough of my code. I think you are missing the string cmd comment. For example if my store procedure is call:DBO.Test. I would need to write cmd="DBO.test". Then do command type equal to store procedure, and blah blah blah
Connection.open();
String cmd="DBO.test"; //the command
Sqlcommand mycommand;
You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding
class.
or try this
System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
System.Text.ASCIIEncoding.ASCII.GetByteCount(string);
Besides the previous post instructions, I had to install the package Microsoft.jQuery.Unobtrusive.Ajax and add to the view the following line
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
I know this isn't as elegant as the other posts, but it's a more straightforward xaml/codebehind example of how to accomplish the same thing.
Xaml:
<StackPanel Orientation="Horizontal">
<TextBox Name="TextBox01" VerticalAlignment="Top" HorizontalAlignment="Left" Width="70" />
<Button Name="Button01" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,0,0,0" />
</StackPanel>
CodeBehind:
Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Button01.IsEnabled = False
Button01.Content = "I am Disabled"
End Sub
Private Sub TextBox01_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBox01.TextChanged
If TextBox01.Text.Trim.Length > 0 Then
Button01.IsEnabled = True
Button01.Content = "I am Enabled"
Else
Button01.IsEnabled = False
Button01.Content = "I am Disabled"
End If
End Sub
In Stored procedure, you return the values using OUT
parameter ONLY. As you have defined two variables in your example:
outstaticip OUT VARCHAR2, outcount OUT NUMBER
Just assign the return values to the out parameters i.e. outstaticip
and outcount
and access them back from calling location. What I mean here is: when you call the stored procedure, you will be passing those two variables as well. After the stored procedure call, the variables will be populated with return values.
If you want to have RETURN value
as return from the PL/SQL call, then use FUNCTION
. Please note that in case, you would be able to return only one variable as return variable.
Short Answer:
Simple rule of thumb: Use POST to create, use PUT to update.
Long Answer:
POST:
PUT:
Longer Answer:
To understand it we need to question why PUT was required, what were the problems PUT was trying to solve that POST couldn't.
From a REST architecture's point of view there is none that matters. We could have lived without PUT as well. But from a client developer's point of view it made his/her life a lot simpler.
Prior to PUT, clients couldn't directly know the URL that the server generated or if all it had generated any or whether the data to be sent to the server is already updated or not. PUT relieved the developer of all these headaches. PUT is idempotent, PUT handles race conditions, and PUT lets the client choose the URL.
Q. List the name of each show, and the number of different times it has been held. List the show which has been held most often first.
event_id show_id event_name judge_id
0101 01 Dressage 01
0102 01 Jumping 02
0103 01 Led in 01
0201 02 Led in 02
0301 03 Led in 01
0401 04 Dressage 04
0501 05 Dressage 01
0502 05 Flag and Pole 02
Ans:
select event_name, count(show_id) as held_times from event
group by event_name
order by count(show_id) desc
You need the <pre></pre>
tags for the line breaks, and the {@code ... }
inside them for generics. But then it's not allowed to place the opening brace on the same line as the <generic>
tag, because then everything will be displayed on 1 line again.
Displays on one line:
* ..
* <pre>
* {@code
* public List<Object> getObjects() {
* return objects;
* }
* </pre>
* ..
Displays with line breaks:
* ..
* <pre>
* {@code
* public List<Object> getObjects()
* {
* return objects;
* }
* </pre>
* ..
Another weird thing is when you paste the closing brace of {@code
, it gets displayed:
* ..
* <pre>
* {@code
* public List<Object> getObjects()
* {
* return objects;
* }
* }
* </pre>
* ..
Output:
public List<Object> getObjects()
{
return objects;
}
}
Should be as simple as:
git reset --hard 56e05f
That'll get you back to that specific point in time.
There were 3 ways to do this:
Method 1: Using iTunes. Yes, you can install .ipa
in iPad, first you have to import that .ipa
to your iTunes. Connect your iPad to iTunes then install application just by click on Install and then Sync.
Method 2: iFunbox
Method 3: Diawi
And incase you a different delimiter other than comma, you can use that as well.
@Value("#{'${my.config.values}'.split(',')}")
private String[] myValues; // could also be a List<String>
and
in your application properties you could have
my.config.values=value1, value2, value3
Maybe the author forgot to give the font a Mac FOND name?
You could also give the "Apple" option in the export dialog a try.
DISCLAIMER: I'm not a IPhone developer!
Also questions is: What is the purpose of giving the relationships in xsd.
Suppose you want to generate some XML for an external party's tool, or similar - how would you know what structure it is allowed to follow to be used correctly for their tool? you write to a schema. Likewise if you want other people to use your tool, you would write a schema for them to follow. It may also be useful for validating your own XML.
It is important to note that object files are assembled to binary code in a format that is relocatable. This is a form which allows the assembled code to be loaded anywhere into memory for use with other programs by a linker.
Instructions that refer to labels will not yet have an address assigned for these labels in the .o file.
These labels will be written as '0' and the assembler creates a relocation record for these unknown addresses. When the file is linked and output to an executable the unknown addresses are resolved and the program can be executed.
You can use the nm tool on an object file to list the symbols defined in a .o file.
If you're not using Homebrew, this is what I just did on MAC OS X Lion (10.7.5):
Get the latest version of the ZSH sourcecode
Untar the download into its own directory then install: ./configure && make && make test && sudo make install
This installs the the zsh binary at /usr/local/bin/zsh
.
You can now use the shell by loading up a new terminal and executing the binary directly, but you'll want to make it your default shell...
To make it your default shell you must first edit /etc/shells
and add the new path. Then you can either run chsh -s /usr/local/bin/zsh
or go to System Preferences > Users & Groups > right click your user > Advanced Options... > and then change "Login shell".
Load up a terminal and check you're now in the correct version with echo $ZSH_VERSION
. (I wasn't at first, and it took me a while to figure out I'd configured iTerm to use a specific shell instead of the system default).
While writing a monitoring tool, i took a slightly different approach.
It felt a bit wasteful to spin up an extra thread just to use WaitForSingleObject or even the RegisterWaitForSingleObject (which does that for you). Since in my case i don't need to know the exact instant a process has closed, just that it indeed HAS closed.
I'm using the GetProcessTimes() instead:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx
GetProcessTimes() will return a FILETIME struct for the process's ExitTime only if the process has actually exited. So is just a matter of checking if the ExitTime struct is populated and if the time isn't 0;
This solution SHOULD account the case where a process has been killed but it's PID was reused by another process. GetProcessTimes needs a handle to the process, not the PID. So the OS should know that the handle is to a process that was running at some point, but not any more, and give you the exit time.
Relying on the ExitCode felt dirty :/
A much more simple solution (thanks to http://daniel.fone.net.nz/blog/2014/12/01/fixing-connection-errors-after-upgrading-postgres/) . I had upgraded to postgres 9.4. In my case, all I needed to do (after a day of googling and not succeeding)
gem uninstall pg
gem uninstall activerecord-postgresql-adapter
bundle install
Restart webrick, and done!
Now with new JavaScript version (ECMAScript 6 http://es6-features.org/#ClassDefinition) there is a better way to submit requests using nodejs and Promise request (http://www.wintellect.com/devcenter/nstieglitz/5-great-features-in-es6-harmony)
Using library: https://github.com/request/request-promise
npm install --save request
npm install --save request-promise
client:
//Sequential execution for node.js using ES6 ECMAScript
var rp = require('request-promise');
rp({
method: 'POST',
uri: 'http://localhost:3000/',
body: {
val1 : 1,
val2 : 2
},
json: true // Automatically stringifies the body to JSON
}).then(function (parsedBody) {
console.log(parsedBody);
// POST succeeded...
})
.catch(function (err) {
console.log(parsedBody);
// POST failed...
});
server:
var express = require('express')
, bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/', function(request, response){
console.log(request.body); // your JSON
var jsonRequest = request.body;
var jsonResponse = {};
jsonResponse.result = jsonRequest.val1 + jsonRequest.val2;
response.send(jsonResponse);
});
app.listen(3000);
You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include
directive. Then you may call the other function.
void MyFunc();
#include "other.h"
int main() {
MyFunc();
}
#include "other.h"
#include <iostream>
void MyFunc() {
std::cout << "Ohai from another .cpp file!";
std::cin.get();
}
Please use this code for selecting date from Two Jquery calendar like Flight Booking site.
Hashtable h=new Hashtable();
h.put("January",0 );
h.put("February",1);
h.put("March",2);
h.put("April",3);
h.put("May",4);
h.put("June",5);
h.put("July",6);
h.put("August",7);
h.put("September",8);
h.put("October",9);
h.put("November",10);
h.put("December",11);
int expMonth;
int expYear;
// Calendar Month and Year
String calMonth = null;
String calYear = null;
boolean dateNotFound;
dateNotFound = true;
expMonth= 5;
expYear = 2014;
while(dateNotFound)
{
calMonth = driver.findElement(By.className("ui-datepicker-month")).getText(); // get the text of month
calYear = driver.findElement(By.className("ui-datepicker-year")).getText();
if(((Integer)h.get(calMonth))+1 == expMonth && (expYear == Integer.parseInt(calYear)))
{
String block="//div[@class='monthBlock first']/table/tbody/tr/td"; // THIS IS FIRST CALENDAR
selectDate(expDate,block);
dateNotFound = false;
}
// parseInt - Converts String to integer and indexof( It will return the index position of String)
else if(((Integer)h.get(calMonth))+1 < expMonth && (expYear == Integer.parseInt(calYear)) || expYear > Integer.parseInt(calYear))
{
String block="//div[@class='monthBlock last']/table/tbody/tr/td"; // THIS IS SECOND CALENDAR
selectDate(expDate,block); // PASSING DATE AND CALENDAR
dateNotFound = false; // Otherwise it will rotate continuously
}
else if((Integer)h.get(calMonth)+1 > expMonth && (expYear == Integer.parseInt(calYear)) || expYear < Integer.parseInt(calYear))
{
System.out.println(" Please enter the date greater than Current date");
dateNotFound = false;
}
}
}
//Thread.sleep(3000);
public static void selectDate(String date,String block) throws IOException
{
String monthblock=block;
List<WebElement> dateWidget = driver.findElements(By.xpath(monthblock));
for (WebElement cell: dateWidget)
{
//Selects Date
if (cell.getText().equals(date))
{
cell.findElement(By.linkText(date)).click();
break;
}
}
//Doubt : How to verify the expected results and how to sort the program
driver.findElement(By.id("SearchBtn")).submit();
//driver.quit();
}
Set FormsBorderStyle
of the Form to None
.
If you do, it's up to you how to implement the dragging and closing functionality of the window.
It's changed now. Replace .Builder()
with .newBuilder()
As of okhttp:3.9.0 the code goes as follows:
OkHttpClient okHttpClient = new OkHttpClient()
.newBuilder()
.connectTimeout(10,TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(30,TimeUnit.SECONDS)
.build();
In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using
<encoder>
<pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern>
</encoder>
the %ex in pattern is what makes the difference
Two variants on what's already been given:
git archive --format=tar --remote=git://git.foo.com/project.git HEAD:path/to/directory filename | tar -O -xf -
and:
git archive --format=zip --remote=git://git.foo.com/project.git HEAD:path/to/directory filename | funzip
These write the file to standard output.
$(':text').attr("disabled", "disabled");
sets all textbox to disabled mode.
You can do in another way like giving each textbox id. By doing this code weight will be more and performance issue will be there.
So better have $(':text').attr("disabled", "disabled");
approach.
Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR
set these variables:
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
export PATH=$JAVA_HOME/bin:$PATH
Run your app and fun :)
(Minor update: put variable value in quote)
SELECT * FROM [server].[database].[schema].[table]
This works for me. SSMS intellisense may still underline this as a syntax error, but it should work if your linked server is configured and your query is otherwise correct.
If you only care about unimodal distributions, consider sth. like this.
public static Optional<Integer> mode(Stream<Integer> stream) {
Map<Integer, Long> frequencies = stream
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
return frequencies.entrySet().stream()
.max(Comparator.comparingLong(Map.Entry::getValue))
.map(Map.Entry::getKey);
}
Well, it would be more accurate to rely on the feature and not a variable value. Especially as there are 2 possible variables for Windows.
function getUserHome() {
return process.env.HOME || process.env.USERPROFILE;
}
EDIT: as mentioned in a more recent answer, https://stackoverflow.com/a/32556337/103396 is the right way to go (require('os').homedir()
).
You may find that using the `group' aes will help you get the result you want. For example:
tu <- expand.grid(Land = gl(2, 1, labels = c("DE", "BB")),
Altersgr = gl(5, 1, labels = letters[1:5]),
Geschlecht = gl(2, 1, labels = c('m', 'w')),
Jahr = 2000:2009)
set.seed(42)
tu$Wert <- unclass(tu$Altersgr) * 200 + rnorm(200, 0, 10)
ggplot(tu, aes(x = Jahr, y = Wert, color = Altersgr, group = Altersgr)) +
geom_point() + geom_line() +
facet_grid(Geschlecht ~ Land)
Which produces the plot found here:
This isn't necessarily exhaustive.
options = {...optionsDefault, ...options};
If authoring code for execution in environments without native support, you may be able to just compile this syntax (as opposed to using a polyfill). (With Babel, for example.)
Less verbose.
When this answer was originally written, this was a proposal, not standardized. When using proposals consider what you'd do if you write code with it now and it doesn't get standardized or changes as it moves toward standardization. This has since been standardized in ES2018.
Literal, not dynamic.
Object.assign()
options = Object.assign({}, optionsDefault, options);
Standardized.
Dynamic. Example:
var sources = [{a: "A"}, {b: "B"}, {c: "C"}];
options = Object.assign.apply(Object, [{}].concat(sources));
// or
options = Object.assign({}, ...sources);
This is the commit that made me wonder.
That's not directly related to what you're asking. That code wasn't using Object.assign()
, it was using user code (object-assign
) that does the same thing. They appear to be compiling that code with Babel (and bundling it with Webpack), which is what I was talking about: the syntax you can just compile. They apparently preferred that to having to include object-assign
as a dependency that would go into their build.
Adding this solution with grep
and basic sh
builtins for those interested in a more portable solution (independent of bash
version; also works with plain old sh
, on non-Linux platforms etc.)
# GLOB matching
gg=svm-grid-ch
case "$gg" in
*grid*) echo $gg ;;
esac
# REGEXP
if echo "$gg" | grep '^....grid*' >/dev/null ; then echo $gg ; fi
if echo "$gg" | grep '....grid*' >/dev/null ; then echo $gg ; fi
if echo "$gg" | grep 's...grid*' >/dev/null ; then echo $gg ; fi
# Extended REGEXP
if echo "$gg" | egrep '(^....grid*|....grid*|s...grid*)' >/dev/null ; then
echo $gg
fi
Some grep
incarnations also support the -q
(quiet) option as an alternative to redirecting to /dev/null
, but the redirect is again the most portable.
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
This is old thread, so I figured for anyone looking for a modern answer, I would suggest using Object.keys();
var myDiv = document.getElementById("myDiv");
var css = {
"font-size": "14px",
"color": "#447",
"font-family": "Arial",
"text-decoration": "underline"
};
function applyInlineStyles(obj) {
var result = "";
Object.keys(obj).forEach(function (prop) {
result += prop + ": " + obj[prop] + "; ";
});
return result;
}
myDiv.style = applyInlineStyles(css);
If using Maven or another framework, and you get this error almost randomly, try a clean install like...
clean install
This is especially likely to work if you wrote the object and you know it has the method.
Since the large post above covers many different SQL approaches for Postgres versions (not only non-9.5 as in the question), I would like to add how to do it in SQLAlchemy if you are using Postgres 9.5. Instead of implementing your own upsert, you can also use SQLAlchemy's functions (which were added in SQLAlchemy 1.1). Personally, I would recommend using these, if possible. Not only because of convenience, but also because it lets PostgreSQL handle any race conditions that might occur.
Cross-posting from another answer I gave yesterday (https://stackoverflow.com/a/44395983/2156909)
SQLAlchemy supports ON CONFLICT
now with two methods on_conflict_do_update()
and on_conflict_do_nothing()
:
Copying from the documentation:
from sqlalchemy.dialects.postgresql import insert
stmt = insert(my_table).values(user_email='[email protected]', data='inserted data')
stmt = stmt.on_conflict_do_update(
index_elements=[my_table.c.user_email],
index_where=my_table.c.user_email.like('%@gmail.com'),
set_=dict(data=stmt.excluded.data)
)
conn.execute(stmt)
There are different ways to check Oracle Database Version. Easiest way is to run the below SQL query to check Oracle Version.
SQL> SELECT * FROM PRODUCT_COMPONENT_VERSION;
SQL> SELECT * FROM v$version;
It's a long time since the question was posted, but I experienced the same issue in a similar scenario. I have a console application and I was consuming a web service and our IIS server where the webservice was placed has windows authentication (NTLM) enabled.
I followed this link and that fixed my problem. Here's the sample code for App.config
:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm" proxyCredentialType="None"
realm=""/>
<message clientCredentialType="UserName" algorithmSuite="Default"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost/servicename/service1.asmx"
binding="basicHttpBinding" bindingConfiguration="ListsSoap"/>
</client>
</system.serviceModel>
CSS has different pseudo selector by which you can achieve such effect. In your case you can use
:active : if you want background color only when the button is clicked and don't want to persist.
:focus: if you want background color untill the focus is on the button.
button:active{
background:olive;
}
and
button:focus{
background:olive;
}
P.S.: Please don't give the number in Id
attribute of html elements.
For some reason the android:textColor only seems to update the title color. You can change the message text color by using a
SpannableString.AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.MyDialogTheme));
AlertDialog dialog = builder.create();
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
dialog.setMessage(wordtoSpan);
dialog.show();
Vikas answer works perfectly for me, here I also add support for the delay (show / hide).
var popover = $('#example');
var options = {
animation : true,
html: true,
trigger: 'manual',
placement: 'right',
delay: {show: 500, hide: 100}
};
popover
.popover(options)
.on("mouseenter", function () {
var t = this;
var popover = $(this);
setTimeout(function () {
if (popover.is(":hover")) {
popover.popover("show");
popover.siblings(".popover").on("mouseleave", function () {
$(t).popover('hide');
});
}
}, options.delay.show);
})
.on("mouseleave", function () {
var t = this;
var popover = $(this);
setTimeout(function () {
if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {
$(t).popover("hide")
}
}, options.delay.hide);
});
Also please pay attention I changed:
if (!$(".popover:hover").length) {
with:
if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {
so that it references exactly at that opened popover, and not any other (since now, through the delay, more than 1 could be open at the same time)
It's quite unclear how you are computing the size ("the size in debug mode"?").
Use printf()
:
printf("the size of c is %u\n", (unsigned int) sizeof c);
Normally you'd print a size_t
value (which is the type sizeof
returns) with %zu
, but if you're using a pre-C99 compiler like Visual Studio that won't work.
You need to find the typedef
statements in your code that define the custom names like uint8
and so on; those are not standard so nobody here can know how they're defined in your code.
New C code should use <stdint.h>
which gives you uint8_t
and so on.
Simply difference between Forward
(ServletRequest request, ServletResponse response) and sendRedirect
(String url) is
forward():
forward()
method is executed in the server side.forward ()
method is provided by the servlet container.sendRedirect()
method.RequestDispatcher
interface.sendRedirect():
sendRedirect()
method is executed in the client side.sendRedirect()
method is provided under HTTP
so it can be used only with HTTP
clients.sendRedirect()
method is slower because when new request is created old request object is lost.HttpServletResponse
.According to the java.io.File
Java Docs
The default temporary-file directory is specified by the system property java.io.tmpdir. On UNIX systems the default value of this property is typically "/tmp" or "/var/tmp"; on Microsoft Windows systems it is typically "c:\temp". A different value may be given to this system property when the Java virtual machine is invoked, but programmatic changes to this property are not guaranteed to have any effect upon the the temporary directory used by this method.
To specify the java.io.tmpdir
System property, you can invoke the JVM as follows:
java -Djava.io.tmpdir=/path/to/tmpdir
By default this value should come from the TMP
environment variable on Windows systems
On OSX and Windows , there are multiple types of clipboards for different types of content. When you copy content in Excel, data is stored in the plaintext and in the html clipboard.
The right way (that doesn't get tripped up by delimiter issues) is to parse the HTML. http://jsbin.com/uwuvan/5 is a simple demo that shows how to get the HTML clipboard. The key is to bind to the onpaste event and read
event.clipboardData.getData('text/html')
If you are running Delphi, or other native compiled CGI, this solution will work:
As other pointed, go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header.
If you have everything allowed, it will still not work. You need to click on "Edit Feature Settings" in Actions (on the right side), and check "Allow unspecified CGI modules", or "Allow unspecified ISAPI modules" respectively.
Click OK
This explains the whole thing:
The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.
The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.
The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.
Also, when you uninstall the package, the first item listed is the directory to the executable.
image.ScaleToFit(500f,30f);
this method keeps the aspect ratio of the image
Try this trick .. use css shadow with (inset) option and make the deep 200px for example
Code:
box-shadow: inset 0px 0px 277px 3px #4c3f37;
.
Also for all browsers:
-moz-box-shadow: inset 0px 0px 47px 3px #4c3f37;
-webkit-box-shadow: inset 0px 0px 47px 3px #4c3f37;
box-shadow: inset 0px 0px 277px 3px #4c3f37;
and increase number to make fill your box :)
Enjoy!
In my case the problem was:
define ('DB_PASSWORD', "MyPassw0rd!'");
(the odd single ' before the double ")
I Hope that this helps you out... Because I tried all the answers but nothing worked perfectly. So, I had to come up with a solution on my own.
#horizontal-style {
padding-inline-start: 0 !important; // Just in case if you find that there is an extra padding at the start of the line
justify-content: space-around;
display: flex;
}
#horizontal-style a {
text-align: center;
color: white;
text-decoration: none;
}
The ld returned 1 exit status
error is the consequence of previous errors. In your example there is an earlier error - undefined reference to 'clrscr'
- and this is the real one. The exit status error just signals that the linking step in the build process encountered some errors. Normally exit status 0
means success, and exit status
> 0 means errors.
When you build your program, multiple tools may be run as separate steps to create the final executable. In your case one of those tools is ld
, which first reports the error it found (clrscr
reference missing), and then it returns the exit status. Since the exit status is > 0, it means an error and is reported.
In many cases tools return as the exit status the number of errors they encountered. So if ld tool finds two errors, its exit status would be 2.
Try
$query = mysql_query("SELECT * FROM users WHERE name = 'Admin' ")or die(mysql_error());
and check if this throw any error.
Then use while($rows = mysql_fetch_assoc($query)):
And finally display it as
echo $name . "<br/>" . $address . "<br/>" . $email . "<br/>" . $subject . "<br/>" . $comment . "<br/><br/>" . ;
Do not user mysql_*
as its deprecated.
For me this problem was caused by a missing ) at the end of an if statement in a function called by the function the error was reported as from. Try scrolling up in the output to find the first error reported by the compiler. Fixing that error may fix this error.
static WebDriver driver;
System.setProperty("webdriver.ie.driver","C:\\(Path)\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.get("EnterURLHere");
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
You could achieve this without having to import traceback:
try:
func1()
except Exception as ex:
trace = []
tb = ex.__traceback__
while tb is not None:
trace.append({
"filename": tb.tb_frame.f_code.co_filename,
"name": tb.tb_frame.f_code.co_name,
"lineno": tb.tb_lineno
})
tb = tb.tb_next
print(str({
'type': type(ex).__name__,
'message': str(ex),
'trace': trace
}))
Output:
{
'type': 'ZeroDivisionError',
'message': 'division by zero',
'trace': [
{
'filename': '/var/playground/main.py',
'name': '<module>',
'lineno': 16
},
{
'filename': '/var/playground/main.py',
'name': 'func1',
'lineno': 11
},
{
'filename': '/var/playground/main.py',
'name': 'func2',
'lineno': 7
},
{
'filename': '/var/playground/my.py',
'name': 'test',
'lineno': 2
}
]
}
Try using RUN /bin/sh
instead of bash.
Simply move the declaration outside of the if block.
@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="";
if (currentstore == "www.mydomain.com")
{
<link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store1_logo.jpg";
}
else
{
<link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store2_logo.gif";
}
}
<a href="@Url.RouteUrl("HomePage")" class="logo"><img alt="" src="@imgsrc"></a>
You could make it a bit cleaner.
@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="/content/images/uploaded/store2_logo.gif";
if (currentstore == "www.mydomain.com")
{
<link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store1_logo.jpg";
}
else
{
<link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
}
}
Answer for a slightly different problem:
You have a sequence of raw unicode that was saved into a str variable:
s_str: str = "\x00\x01\x00\xc0\x01\x00\x00\x00\x04"
You need to be able to get the byte literal of that unicode (for struct.unpack(), etc.)
s_bytes: bytes = b'\x00\x01\x00\xc0\x01\x00\x00\x00\x04'
Solution:
s_new: bytes = bytes(s, encoding="raw_unicode_escape")
Reference (scroll up for standard encodings):
You can use the getters of java.time.LocalDateTime
for that.
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
int millis = now.get(ChronoField.MILLI_OF_SECOND); // Note: no direct getter available.
System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
Or, when you're not on Java 8 yet, make use of java.util.Calendar
.
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
Either way, this prints as of now:
2010-04-16 15:15:17.816
To convert an int
to String
, make use of String#valueOf()
.
If your intent is after all to arrange and display them in a human friendly string format, then better use either Java8's java.time.format.DateTimeFormatter
(tutorial here),
LocalDateTime now = LocalDateTime.now();
String format1 = now.format(DateTimeFormatter.ISO_DATE_TIME);
String format2 = now.atZone(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME);
String format3 = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.ENGLISH));
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
or when you're not on Java 8 yet, use java.text.SimpleDateFormat
:
Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp!
String format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(now);
String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).format(now);
String format3 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH).format(now);
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
Either way, this yields:
2010-04-16T15:15:17.816 Fri, 16 Apr 2010 15:15:17 GMT 20100416151517
You want to be using java.lang.reflect.Constructor.newInstance(Object...)
I've implemented a different method to check for primes because:
Here is my implementation:
public static BigInteger IntegerSquareRoot(BigInteger value)
{
if (value > 0)
{
int bitLength = value.ToByteArray().Length * 8;
BigInteger root = BigInteger.One << (bitLength / 2);
while (!IsSquareRoot(value, root))
{
root += value / root;
root /= 2;
}
return root;
}
else return 0;
}
private static Boolean IsSquareRoot(BigInteger n, BigInteger root)
{
BigInteger lowerBound = root * root;
BigInteger upperBound = (root + 1) * (root + 1);
return (n >= lowerBound && n < upperBound);
}
static bool IsPrime(BigInteger value)
{
Console.WriteLine("Checking if {0} is a prime number.", value);
if (value < 3)
{
if (value == 2)
{
Console.WriteLine("{0} is a prime number.", value);
return true;
}
else
{
Console.WriteLine("{0} is not a prime number because it is below 2.", value);
return false;
}
}
else
{
if (value % 2 == 0)
{
Console.WriteLine("{0} is not a prime number because it is divisible by 2.", value);
return false;
}
else if (value == 5)
{
Console.WriteLine("{0} is a prime number.", value);
return true;
}
else if (value % 5 == 0)
{
Console.WriteLine("{0} is not a prime number because it is divisible by 5.", value);
return false;
}
else
{
// The only way this number is a prime number at this point is if it is divisible by numbers ending with 1, 3, 7, and 9.
AutoResetEvent success = new AutoResetEvent(false);
AutoResetEvent failure = new AutoResetEvent(false);
AutoResetEvent onesSucceeded = new AutoResetEvent(false);
AutoResetEvent threesSucceeded = new AutoResetEvent(false);
AutoResetEvent sevensSucceeded = new AutoResetEvent(false);
AutoResetEvent ninesSucceeded = new AutoResetEvent(false);
BigInteger squareRootedValue = IntegerSquareRoot(value);
Thread ones = new Thread(() =>
{
for (BigInteger i = 11; i <= squareRootedValue; i += 10)
{
if (value % i == 0)
{
Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
failure.Set();
}
}
onesSucceeded.Set();
});
ones.Start();
Thread threes = new Thread(() =>
{
for (BigInteger i = 3; i <= squareRootedValue; i += 10)
{
if (value % i == 0)
{
Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
failure.Set();
}
}
threesSucceeded.Set();
});
threes.Start();
Thread sevens = new Thread(() =>
{
for (BigInteger i = 7; i <= squareRootedValue; i += 10)
{
if (value % i == 0)
{
Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
failure.Set();
}
}
sevensSucceeded.Set();
});
sevens.Start();
Thread nines = new Thread(() =>
{
for (BigInteger i = 9; i <= squareRootedValue; i += 10)
{
if (value % i == 0)
{
Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
failure.Set();
}
}
ninesSucceeded.Set();
});
nines.Start();
Thread successWaiter = new Thread(() =>
{
AutoResetEvent.WaitAll(new WaitHandle[] { onesSucceeded, threesSucceeded, sevensSucceeded, ninesSucceeded });
success.Set();
});
successWaiter.Start();
int result = AutoResetEvent.WaitAny(new WaitHandle[] { success, failure });
try
{
successWaiter.Abort();
}
catch { }
try
{
ones.Abort();
}
catch { }
try
{
threes.Abort();
}
catch { }
try
{
sevens.Abort();
}
catch { }
try
{
nines.Abort();
}
catch { }
if (result == 1)
{
return false;
}
else
{
Console.WriteLine("{0} is a prime number.", value);
return true;
}
}
}
}
Update: If you want to implement a solution with trial division more rapidly, you might consider having a cache of prime numbers. A number is only prime if it is not divisible by other prime numbers that are up to the value of its square root. Other than that, you might consider using the probabilistic version of the Miller-Rabin primality test to check for a number's primality if you are dealing with large enough values (taken from Rosetta Code in case the site ever goes down):
// Miller-Rabin primality test as an extension method on the BigInteger type.
// Based on the Ruby implementation on this page.
public static class BigIntegerExtensions
{
public static bool IsProbablePrime(this BigInteger source, int certainty)
{
if(source == 2 || source == 3)
return true;
if(source < 2 || source % 2 == 0)
return false;
BigInteger d = source - 1;
int s = 0;
while(d % 2 == 0)
{
d /= 2;
s += 1;
}
// There is no built-in method for generating random BigInteger values.
// Instead, random BigIntegers are constructed from randomly generated
// byte arrays of the same length as the source.
RandomNumberGenerator rng = RandomNumberGenerator.Create();
byte[] bytes = new byte[source.ToByteArray().LongLength];
BigInteger a;
for(int i = 0; i < certainty; i++)
{
do
{
// This may raise an exception in Mono 2.10.8 and earlier.
// http://bugzilla.xamarin.com/show_bug.cgi?id=2761
rng.GetBytes(bytes);
a = new BigInteger(bytes);
}
while(a < 2 || a >= source - 2);
BigInteger x = BigInteger.ModPow(a, d, source);
if(x == 1 || x == source - 1)
continue;
for(int r = 1; r < s; r++)
{
x = BigInteger.ModPow(x, 2, source);
if(x == 1)
return false;
if(x == source - 1)
break;
}
if(x != source - 1)
return false;
}
return true;
}
}
Since PHP 5.4 you can use http_response_code.
http_response_code(404);
This will take care of setting the proper HTTP headers.
If you are running PHP < 5.4 then you have two options:
http_response_code
function implemented in PHP.There is a hasClass function
if($('#popup p').hasClass('filled-text'))
If you are using Linux OS:
matplotlib==1.3.1
from requirements.txt
sudo apt-get install python-matplotlib
pip install -r requirements.txt
(Python 2), or pip3 install -r requirements.txt
(Python 3)pip freeze > requirements.txt
If you are using Windows OS:
python -m pip install -U pip setuptools
python -m pip install matplotlib
If you have access to manipulate the code of the site you are loading, the following should provide a comprehensive method to updating the height of the iframe
container anytime the height of the framed content changes.
Add the following code to the pages you are loading (perhaps in a header). This code sends a message containing the height of the HTML container any time the DOM is updated (if you're lazy loading) or the window is resized (when the user modifies the browser).
window.addEventListener("load", function(){
if(window.self === window.top) return; // if w.self === w.top, we are not in an iframe
send_height_to_parent_function = function(){
var height = document.getElementsByTagName("html")[0].clientHeight;
//console.log("Sending height as " + height + "px");
parent.postMessage({"height" : height }, "*");
}
// send message to parent about height updates
send_height_to_parent_function(); //whenever the page is loaded
window.addEventListener("resize", send_height_to_parent_function); // whenever the page is resized
var observer = new MutationObserver(send_height_to_parent_function); // whenever DOM changes PT1
var config = { attributes: true, childList: true, characterData: true, subtree:true}; // PT2
observer.observe(window.document, config); // PT3
});
Add the following code to the page that the iframe is stored on. This will update the height of the iframe, given that the message came from the page that that iframe loads.
<script>
window.addEventListener("message", function(e){
var this_frame = document.getElementById("healthy_behavior_iframe");
if (this_frame.contentWindow === e.source) {
this_frame.height = e.data.height + "px";
this_frame.style.height = e.data.height + "px";
}
})
</script>
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day, 0, 0, 0, 0);
return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
}
According to this JSPerf test, they differ in speed. But unless you're going to use them in huge amounts, any of them should perform fine.
For completeness: As asawyer already mentioned, you can also use the .toString()
method.
Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.
Assume your code is looking for the file say app.properties. Copy this file to any dir and add this dir to classpath, by creating a setenv.sh in the bin dir of tomcat.
In your setenv.sh of tomcat( if this file is not existing, create one , tomcat will load this setenv.sh file.
#!/bin/sh
CLASSPATH="$CLASSPATH:/home/user/config_my_prod/"
You should not have your properties files in ./webapps//WEB-INF/classes/app.properties
Tomcat class loader will override the with the one from WEB-INF/classes/
A good read: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html
You are single quoting your SQL statement which is making the variables text instead of variables.
$sql = "SELECT *
FROM $usertable
WHERE PartNumber = $partid";
In android studio, You can use bellow process to create & Read QR Code &image look like bellw
Add library in app.gradle
compile 'com.google.zxing:core:3.2.1'
compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
In activity.main xml use bellow..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.enamul.qrcode.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical">
<EditText
android:id="@+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Enter Text Here" />
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="@+id/editText"
android:text="Click Here TO generate qr code"
android:textAllCaps="false"
android:textSize="16sp" />
<Button
android:id="@+id/btnScan"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="@+id/editText"
android:text="Scan Your QR Code"
android:textAllCaps="false"
android:textSize="16sp" />
<TextView
android:id="@+id/tv_qr_readTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="@+id/button"
android:src="@android:drawable/ic_dialog_email" />
</LinearLayout>
</LinearLayout>
In MainActivity you can use bellow code
public class MainActivity extends AppCompatActivity {
ImageView imageView;
Button button;
Button btnScan;
EditText editText;
String EditTextValue ;
Thread thread ;
public final static int QRcodeWidth = 350 ;
Bitmap bitmap ;
TextView tv_qr_readTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView);
editText = (EditText)findViewById(R.id.editText);
button = (Button)findViewById(R.id.button);
btnScan = (Button)findViewById(R.id.btnScan);
tv_qr_readTxt = (TextView) findViewById(R.id.tv_qr_readTxt);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!editText.getText().toString().isEmpty()){
EditTextValue = editText.getText().toString();
try {
bitmap = TextToImageEncode(EditTextValue);
imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
else{
editText.requestFocus();
Toast.makeText(MainActivity.this, "Please Enter Your Scanned Test" , Toast.LENGTH_LONG).show();
}
}
});
btnScan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
}
Bitmap TextToImageEncode(String Value) throws WriterException {
BitMatrix bitMatrix;
try {
bitMatrix = new MultiFormatWriter().encode(
Value,
BarcodeFormat.DATA_MATRIX.QR_CODE,
QRcodeWidth, QRcodeWidth, null
);
} catch (IllegalArgumentException Illegalargumentexception) {
return null;
}
int bitMatrixWidth = bitMatrix.getWidth();
int bitMatrixHeight = bitMatrix.getHeight();
int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];
for (int y = 0; y < bitMatrixHeight; y++) {
int offset = y * bitMatrixWidth;
for (int x = 0; x < bitMatrixWidth; x++) {
pixels[offset + x] = bitMatrix.get(x, y) ?
getResources().getColor(R.color.QRCodeBlackColor):getResources().getColor(R.color.QRCodeWhiteColor);
}
}
Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);
bitmap.setPixels(pixels, 0, 350, 0, 0, bitMatrixWidth, bitMatrixHeight);
return bitmap;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.e("Scan*******", "Cancelled scan");
} else {
Log.e("Scan", "Scanned");
tv_qr_readTxt.setText(result.getContents());
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
}
You can download full source code from GitHub. GitHub link is : https://github.com/enamul95/QRCode
For me, it was permission issue. Docker run is called with a user profile but root is the user inside the container. The solution was to make curl write to /tmp since that has write permission for all users , not just root.
I used the -o option.
-o /tmp/file_to_download
Use a return statement!
return;
or
if (condition) return;
You don't need to (and can't) specify any values, if your method returns void
.
As I have noticed this error occurs under two circumstances,
so use, either np.array(y_test) for y_true in scores or y_test.reset_index(drop=True)
Hope this helps.
In P4V click View > Workspaces
If the workspace to be deleted is not visible in the list you may have to uncheck the box Show only workspaces available for use on this computer
Right-click the workspace to be deleted and choose Edit Workspace 'My_workspace'
On the Advanced tab uncheck the box Locked: only the owner can edit workspace settings > then click OK
Now back on the Workspaces tab of Perforce right-click the workspace to be deleted and choose Delete Workspace 'My_workspace'
P4V should remove the item from the drop-down list when clicking on it.
There is a case where a previously deleted workspace remains in the drop-down list, and P4V displays the following error:
P4V Workspace Switch Error. This workspace cannot be used on this computer either because the host field does not match your computer name or the workspace root cannot be used on this computer.
If this error occurs, the workspace(possibly on another host) may have only been unloaded. Click the P4V Workspaces Recycle bin
In the resulting Unloaded Workspaces window right-click the offending workspace and choose Delete Workspace 'My_workspace'. P4V should now remove the workspace item from the drop-down list.
$(document).ready(function() {
$('#media').carousel({
pause: true,
interval: 40000,
});
});
By using the above script, you will be able to move the images automaticaly
$(document).ready(function() {
$('#media').carousel({
pause: true,
interval: false,
});
});
By using the above script, auto-rotation
will be blocked because interval
is false
Here is a solution that also takes in account if you are using Ajax requests.
using System;
using System.Web.Mvc;
using System.Web.Routing;
namespace YourNamespace{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeCustom : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext context) {
if (YourAuthorizationCheckGoesHere) {
string area = "";// leave empty if not using area's
string controller = "ControllerName";
string action = "ActionName";
var urlHelper = new UrlHelper(context.RequestContext);
if (context.HttpContext.Request.IsAjaxRequest()){ // Check if Ajax
if(area == string.Empty)
context.HttpContext.Response.Write($"<script>window.location.reload('{urlHelper.Content(System.IO.Path.Combine(controller, action))}');</script>");
else
context.HttpContext.Response.Write($"<script>window.location.reload('{urlHelper.Content(System.IO.Path.Combine(area, controller, action))}');</script>");
} else // Non Ajax Request
context.Result = new RedirectToRouteResult(new RouteValueDictionary( new{ area, controller, action }));
}
base.OnActionExecuting(context);
}
}
}
Use:
git log --graph --abbrev-commit --decorate --first-parent <branch_name>
It is only for the target branch (of course --graph, --abbrev-commit --decorate are more polishing).
The key option is --first-parent
: "Follow only the first parent commit upon seeing a merge commit" (https://git-scm.com/docs/git-log)
It prevents the commit forks from being displayed.
Share your folder for "everyone" or some specific group and try this:
<a href="file://YOURSERVERNAME/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf"> Download PDF </a>
_x000D_
When you use %
for setting heights or widths, always set the widths/heights of parent elements as well:
.table {_x000D_
display: table;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
border: 2px solid black;_x000D_
vertical-align: top;_x000D_
display: table-cell;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.container {_x000D_
height: 100%;_x000D_
border: 2px solid green;_x000D_
-moz-box-sizing: border-box;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="cell">_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
</div>_x000D_
<div class="cell">_x000D_
<div class="container">Text</div>_x000D_
</div>_x000D_
</div>
_x000D_
title
is a local variable. They only exists within its scope (current block)
@title
is an instance variable - and is available to all methods within the class.
You can read more here: http://strugglingwithruby.blogspot.dk/2010/03/variables.html
In Ruby on Rails - declaring your variables in your controller as instance variables (@title
) makes them available to your view.
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
When you click on hide me
, both a and span clicks are triggering. Since the page is redirecting to another, you cannot see the working of hide()
You can see this for more clarification
grep -A20 -B20 pattern file.txt
Search pattern and show 20 lines after and before pattern
For me neither the @Rule
nor the @RunWith(MockitoJUnitRunner.Silent.class)
suggestions worked. It was a legacy project where we upgraded to mockito-core 2.23.0.
We could get rid of the UnnecessaryStubbingException
by using:
Mockito.lenient().when(mockedService.getUserById(any())).thenReturn(new User());
instead of:
when(mockedService.getUserById(any())).thenReturn(new User());
Needless to say that you should rather look at the test code, but we needed to get the stuff compiled and the tests running first of all ;)
if(is_array($arr) && count($arr) > 1)
Just to be sure that $arr is indeed an array.
sizeof
is an alias of count
, I prefer to use count because:
All of these solutions suffer from one of two problems. Either the solution isn't perfectly accurate due to rounding errors, leap days and seconds, etc. or you end up looping over the number of days in between your two unknown dates.
This solution solves the first problem, and improves the second by a factor of roughly 365, better if you know what your max range is.
/**
* @param thisDate
* @param thatDate
* @param maxDays
* set to -1 to not set a max
* @returns number of days covered between thisDate and thatDate, inclusive, i.e., counting both
* thisDate and thatDate as an entire day. Will short out if the number of days exceeds
* or meets maxDays
*/
public static int daysCoveredByDates(Date thisDate, Date thatDate, int maxDays) {
//Check inputs
if (thisDate == null || thatDate == null) {
return -1;
}
//Set calendar objects
Calendar startCal = Calendar.getInstance();
Calendar endCal = Calendar.getInstance();
if (thisDate.before(thatDate)) {
startCal.setTime(thisDate);
endCal.setTime(thatDate);
}
else {
startCal.setTime(thatDate);
endCal.setTime(thisDate);
}
//Get years and dates of our times.
int startYear = startCal.get(Calendar.YEAR);
int endYear = endCal.get(Calendar.YEAR);
int startDay = startCal.get(Calendar.DAY_OF_YEAR);
int endDay = endCal.get(Calendar.DAY_OF_YEAR);
//Calculate the number of days between dates. Add up each year going by until we catch up to endDate.
while (startYear < endYear && maxDays >= 0 && endDay - startDay + 1 < maxDays) {
endDay += startCal.getActualMaximum(Calendar.DAY_OF_YEAR); //adds the number of days in the year startDate is currently in
++startYear;
startCal.set(Calendar.YEAR, startYear); //reup the year
}
int days = endDay - startDay + 1;
//Honor the maximum, if set
if (maxDays >= 0) {
days = Math.min(days, maxDays);
}
return days;
}
If you need days between dates (uninclusive of the latter date), just get rid of the + 1
when you see endDay - startDay + 1
.
You can use AppendAllText
instead:
File.AppendAllText(filePath, csv);
As the documentation of WriteAllText
says:
If the target file already exists, it is overwritten
Also, note that your current code is not using proper new lines, for example in Notepad you'll see it all as one long line. Change the code to this to have proper new lines:
string csv = string.Format("{0},{1}{2}", first, image, Environment.NewLine);
I have seen this error occur when the plugins that are needed are not specifically mentioned in the pom. So
mvn clean install
will give the exception if this is not added:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
Likewise,
mvn clean install deploy
will fail on the same exception if something like this is not added:
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.1</version>
<executions>
<execution>
<id>default-deploy</id>
<phase>deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>
It makes sense, but a clearer error message would be welcome
LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
tv.setText("test");
this.m_vwJokeLayout.addView(tv);
You can change lparams according to your needs
Have you considered doing this from the layout.xml
? You could set for your ImageView
the ScaleType to android:scaleType="centerCrop"
and set the dimensions of the image in the ImageView
inside the layout.xml
.
document.getElementById('loginSubmit').submit();
or, use the same code as the onclick
handler:
changeAction('submitInput','loginForm');
document.forms['loginForm'].submit();
(Though that onclick
handler is kind of stupidly-written: document.forms['loginForm']
could be replaced with this
.)
Use List.AddRange(collection As IEnumerable(Of T)) method.
It allows you to append at the end of your list another collection/list.
Example:
List<string> initialList = new List<string>();
// Put whatever you want in the initial list
List<string> listToAdd = new List<string>();
// Put whatever you want in the second list
initialList.AddRange(listToAdd);
Yes, Its possible in SQL, but we can't set more than one primary keys in MsAccess. Then, I don't know about the other databases.
CREATE TABLE CHAPTER (
BOOK_ISBN VARCHAR(50) NOT NULL,
IDX INT NOT NULL,
TITLE VARCHAR(100) NOT NULL,
NUM_OF_PAGES INT,
PRIMARY KEY (BOOK_ISBN, IDX)
);
jdk is necessary to compile to code and convert java code to byte codes while jre is necessary for executing the byte codes.
when you create empty array values ARE NOT undefined, they are EMPTY
var arr = new Array(10); // (10) [empty × 10]
but when you get item by index receive undefined
arr[0]; // undefined
so you can't know by === comparing if they are undefined or empty
we can make it by using JSON.stringify, converting whole array it replaces empty values with null
JSON.stringify(arr); // "[null,null,null,null,null,null,null,null,null,null]"
JSON.stringify(arr[0]); // but for single item it returns undefined
so real check for empty value:
arr[0] !== null && JSON.stringify(arr.map(item => !item)).slice(1, -1).split(',')[0] === 'null'
false
instead existing values (ensure stringified structure to be comma-separated without redundant commas)null
Not what you asked but may be useful nevertheless.
Of course you can do the same thing with matrix formulas. Just read the result of the cell that contains:
Cell A1="Text to search"
Cells A2:C20=Range to search for
=COUNT(SEARCH(A1;A2:C20;1))
Remember that entering matrix formulas needs CTRL+SHIFT+ENTER, not just ENTER. After, it should look like :
{=COUNT(SEARCH(A1;A2:C20;1))}
At the end of your for() loop, you can use the savefig()
function instead of plt.show() and set the name, dpi and format of your figure.
E.g. 1000 dpi and eps format are quite a good quality, and if you want to save every picture at folder ./ with names 'Sample1.eps', 'Sample2.eps', etc. you can just add the following code:
for fname in glob("./*.txt"):
# Your previous code goes here
[...]
plt.savefig("./{}.eps".format(fname), bbox_inches='tight', format='eps', dpi=1000)
I found "kill -0" does not work if the process is owned by root (or other), so I used pgrep and came up with:
while pgrep -u root process_name > /dev/null; do sleep 1; done
This would have the disadvantage of probably matching zombie processes.
Below is code snippet you can use to delete the bucket,
import boto3, botocore
from botocore.exceptions import ClientError
s3 = boto3.resource("s3",aws_access_key_id='Your-Access-Key',aws_secret_access_key='Your-Secret-Key')
s3.Object('Bucket-Name', 'file-name as key').delete()
bool vExist = false;
int vSelectValue = 1;
List<int> vList = new List<int>();
vList.Add(1);
vList.Add(2);
IEnumerable vRes = (from n in vListwhere n == vSelectValue);
if (vRes.Count > 0) {
vExist = true;
}
CharSequence
is a contract (interface), and String
is an implementation of this contract.
public final class String extends Object
implements Serializable, Comparable<String>, CharSequence
The documentation for CharSequence
is:
A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences. A char value represents a character in the Basic Multilingual Plane (BMP) or a surrogate. Refer to Unicode Character Representation for details.
Add below cd line in your shellscript this:
exec $SHELL
The problem with the CSV format, is there's not one spec, there are several accepted methods, with no way of distinguishing which should be used (for generate/interpret). I discussed all the methods to escape characters (newlines in that case, but same basic premise) in another post. Basically it comes down to using a CSV generation/escaping process for the intended users, and hoping the rest don't mind.
start cmd /k
did the magic for me. I actually used it for preparing cordova phonegap app it runs the command, shows the result and waits for the user to close it. Below is the simple example
start cmd /k echo Hello, World!
What I did use in my case
start cmd /k cordova prepare
Update
You could even have a title for this by using
start "My Title" echo Hello, World!
abs(x-y)
will do exactly what you're looking for:
In [1]: abs(1-2)
Out[1]: 1
In [2]: abs(2-1)
Out[2]: 1
The MyKey class must implement Serializable
if you are using @IdClass
From:
it could be:
.html()
In an HTML document, .html()
can be used to get the contents of any element.
.text()
Unlike the .html()
method, .text()
can be used in both XML and HTML documents. The result of the .text()
method is a string containing the combined text of all matched elements.
.val()
The .val()
method is primarily used to get the values of form elements such as input
, select
and textarea
. When called on an empty collection, it returns undefined
.
$db->getProfiler()->setEnabled(true);
// your code
$this->update('table', $data, $where);
Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQuery());
Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQueryParams());
$db->getProfiler()->setEnabled(false);
You could also use box-shadow
property with higher value of blur and rgba()
color to set opacity level.
Sounds like a better choice in your case.
box-shadow: 0 30px 40px rgba(0,0,0,.1);
if you add a jpg,png,pdf picture, you should use pdflatex to compile it.
Please check Michael answer and vote for it. It is the right way to check open ports. Netstat and other tools are not any use if you are developing services or daemons. For instance, I am crating modbus TCP server and client services for an industrial network. The services can listen to any port, but the question is whether that port is open? The program is going to be used in different places, and I cannot check them all manually, so this is what I did:
from contextlib import closing
import socket
class example:
def __init__():
self.machine_ip = socket.gethostbyname(socket.gethostname())
self.ready:bool = self.check_socket()
def check_socket(self)->bool:
result:bool = True
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
modbus_tcp_port:int = 502
if not sock.connect_ex((self.machine_ip, modbus_tcp_port)) == 0:
result = False
return result
Yes. Youtube API is the best resource for this.
There are 3 way to embed a video:
<iframe>
tagsDEPRECATED
I think you are looking for the second one of them:
The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.
<div id="ytplayer"></div>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE'
});
}
</script>
Here are some instructions where you may take a look when starting using the API.
An embed example without using iframe
is to use <object>
tag:
<object width="640" height="360">
<param name="movie" value="http://www.youtube.com/embed/yt-video-id?html5=1&rel=0&hl=en_US&version=3"/
<param name="allowFullScreen" value="true"/>
<param name="allowscriptaccess" value="always"/>
<embed width="640" height="360" src="http://www.youtube.com/embed/yt-video-id?html5=1&rel=0&hl=en_US&version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>
(replace yt-video-id
with your video id)
encode:
$("<textarea/>").html('<a>').html(); // return '<a>'
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea/>
_x000D_
decode:
$("<textarea/>").html('<a>').val() // return '<a>'
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea/>
_x000D_
In the manifest:
<activity android:name=".YourActivity"
android:screenOrientation="portrait"
android:configChanges="orientation|screenSize">
In your activity:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.your_activity_layout);
private String removeScript(String content) {
Pattern p = Pattern.compile("<script[^>]*>(.*?)</script>",
Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
return p.matcher(content).replaceAll("");
}
w.replace({'female':{'female':1, 'male':0}}, inplace = True)
The above code will replace 'female' with 1 and 'male' with 0, only in the column 'female'
Technically, I have seen HTTP GET will have issues if the URL length goes beyond 2000 characters. In that case, it's better to use HTTP POST or split the URL.
For anyone stumbling across the same issue:
I fixed the problem by cloning the repo again at another location. I then copied my whole src dir (without .git dir obviously) from the corrupted repo into the freshly cloned repo. Thus I had all the recent changes and a clean and working repository.
Replace:
myBinding.Source = ViewModel.SomeString;
with:
myBinding.Source = ViewModel;
Example:
Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);
Your source should be just ViewModel
, the .SomeString
part is evaluated from the Path
(the Path
can be set by the constructor or by the Path
property).
The SimpleDateFormat class allows you to parse a String
into a java.util.Date
object. Once you have the Date object, you can get the milliseconds since the epoch by calling Date.getTime()
.
The full example:
String myDate = "2014/10/29 18:10:45";
//creates a formatter that parses the date in the given format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long timeInMillis = date.getTime();
Note that this gives you a long
and not a double, but I think that's probably what you intended. The documentation for the SimpleDateFormat
class has tons on information on how to set it up to parse different formats.
Sorry I know this is an old one but still felt like helping out ^_^
Maybe it's the way I read this but assuming the excel sheet 1 is called "London" and has this information; B5="Marleybone" B6="Paddington" B7="Victoria" B8="Hammersmith". And the excel sheet 2 is called "Nottingham" and has this information; C5="Alverton" C6="Annesley" C7="Arnold" C8="Askham". Then I think this code below would work. ^_^
$xlCellTypeLastCell = 11
$startRow = 5
$excel = new-object -com excel.application
$wb = $excel.workbooks.open("C:\users\administrator\my_test.xls")
for ($i = 1; $i -le $wb.sheets.count; $i++)
{
$sh = $wb.Sheets.Item($i)
$endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
$col = $col + $i - 1
$city = $wb.Sheets.Item($i).name
$rangeAddress = $sh.Cells.Item($startRow, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
$sh.Range($rangeAddress).Value2 | foreach{
New-Object PSObject -Property @{City = $city; Area=$_}
}
}
$excel.Workbooks.Close()
This should be the output (without the commas):
City, Area
---- ----
London, Marleybone
London, Paddington
London, Victoria
London, Hammersmith
Nottingham, Alverton
Nottingham, Annesley
Nottingham, Arnold
Nottingham, Askham
Another interesting usecase for split in Hive is when, for example, a column ipname
in the table has a value "abc11.def.ghft.com" and you want to pull "abc11" out:
SELECT split(ipname,'[\.]')[0] FROM tablename;
There are many ways, for example:
Method one:
public string test()
{
string ErrMsg = string.Empty;
try
{
int num = int.Parse("gagw");
}
catch (Exception ex)
{
ErrMsg = ex.Message;
}
return ErrMsg
}
Method two:
public void test(ref string ErrMsg )
{
ErrMsg = string.Empty;
try
{
int num = int.Parse("gagw");
}
catch (Exception ex)
{
ErrMsg = ex.Message;
}
}
Just wanted to put an update. page-break-after
is a legacy property now.
Official page states
This property has been replaced by the break-after property.
PRN solution works only for simple data in the cells, for me it cuts only first 6 signs from 200 characters cell.
These are the main file formats in Excel 2007-2016, Note: In Excel for the Mac the values are +1
51 = xlOpenXMLWorkbook (without macro's in 2007-2016, xlsx)
52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2016, xlsm)
50 = xlExcel12 (Excel Binary Workbook in 2007-2016 with or without macro's, xlsb)
56 = xlExcel8 (97-2003 format in Excel 2007-2016, xls)
From XlFileFormat FileFormat Property
Keep in mind others FileFormatNumbers for SaveAs method:
FileExtStr = ".csv": FileFormatNum = 6
FileExtStr = ".txt": FileFormatNum = -4158
FileExtStr = ".prn": FileFormatNum = 36
Straight from the ECMA-262, Fifth Edition ECMAScript Specification:
7.9.1 Rules of Automatic Semicolon Insertion
There are three basic rules of semicolon insertion:
- When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
- The offending token is separated from the previous token by at least one
LineTerminator
.- The offending token is }.
- When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript
Program
, then a semicolon is automatically inserted at the end of the input stream.- When, as the program is parsed from left to right, a token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation "[no
LineTerminator
here]" within the restricted production (and therefore such a token is called a restricted token), and the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.However, there is an additional overriding condition on the preceding rules: a semicolon is never inserted automatically if the semicolon would then be parsed as an empty statement or if that semicolon would become one of the two semicolons in the header of a for statement (see 12.6.3).
First off, the arrays are pointless, let's get rid of them: all they are doing is providing values for mock data. How you construct mock objects has been debated ad nauseum, but clearly, the code to create the fake Athletes should be inside of a unit test. I would use Joshua Bloch's static builder for the Athlete class, but you only have two attributes right now, so just pass those in a Constructor. Would look like this:
class Athlete {
private String name;
private String country;
private List<Dive> dives;
public Athlete(String name, String country){
this.name = name;
this.country = country;
}
public String getName(){
return this.name;
}
public String getCountry(){
return this.country;
}
public String getDives(){
return this.dives;
}
public void addDive(Dive dive){
this.dives.add(dive);
}
}
Then for the Dive class:
class Dive {
private Athlete athlete;
private Date date;
private double score;
public Dive(Athlete athlete, double score){
this.athlete = athlete;
this.score = score;
this.date = new Date();
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
}
Then make a unit test and just construct the classes, and manipulate them, make sure that they are working. Right now they don't do anything so all you could do is assert that they are retaining the Dives that you are putting in them. Example:
@Test
public void testThatDivesRetainInformation(){
Athlete art = new Athlete("Art", "Canada");
Dive art1 = new Dive(art, 8.5);
Dive art2 = new Dive(art, 8.0);
Dive art3 = new Dive(art, 8.8);
Dive art4 = new Dive(art, 9.2);
assertThat(art.getDives().size(), is(5));
}
Then you could go through and add tests for things like, making sure that you can't construct a dive without an athlete, etc.
You could move construction of the athletes into the setup method of the test so you could use it all over the place. Most IDEs have support for doing that with a refactoring.
Someone should mention that in the question there is a little trap. #ifdef
will only check if the following symbol has been defined via #define
or by command line, but its value (its substitution in fact) is irrelevant. You could even write
#define one
precompilers accept that.
But if you use #if
it's another thing.
#define one 0
#if one
printf("one evaluates to a truth ");
#endif
#if !one
printf("one does not evaluate to truth ");
#endif
will give one does not evaluate to truth
. The keyword defined
allows to get the desired behaviour.
#if defined(one)
is therefore equivalent to #ifdef
The advantage of the #if
construct is to allow a better handling of code paths, try to do something like that with the old #ifdef
/#ifndef
pair.
#if defined(ORA_PROC) || defined(__GNUC) && __GNUC_VERSION > 300
Accepted answer is certainly a good solution, but here is the way I went about generating a CSV and serving it from a view.
Thought it was worth while putting this here as it took me a little bit of fiddling to get all the desirable behaviour (overwrite existing file, storing to the right spot, not creating duplicate files etc).
Django 1.4.1
Python 2.7.3
#Model
class MonthEnd(models.Model):
report = models.FileField(db_index=True, upload_to='not_used')
import csv
from os.path import join
#build and store the file
def write_csv():
path = join(settings.MEDIA_ROOT, 'files', 'month_end', 'report.csv')
f = open(path, "w+b")
#wipe the existing content
f.truncate()
csv_writer = csv.writer(f)
csv_writer.writerow(('col1'))
for num in range(3):
csv_writer.writerow((num, ))
month_end_file = MonthEnd()
month_end_file.report.name = path
month_end_file.save()
from my_app.models import MonthEnd
#serve it up as a download
def get_report(request):
month_end = MonthEnd.objects.get(file_criteria=criteria)
response = HttpResponse(month_end.report, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=report.csv'
return response
What they mean by non-false is:
return true;
So this code:
var arr = ["one", "two", "three", "four", "five"];_x000D_
$.each(arr, function(i) {_x000D_
if (arr[i] == 'three') {_x000D_
return true;_x000D_
}_x000D_
console.log(arr[i]);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
will log one
, two
, four
, five
.
You can use gitk [filename]
to see the changes log