You have about 98% right. The only issue is that you're trying to print out an String[] which does not print the way you'd like. Instead try this...
for (String[] s : myEntries) {
System.out.print("Next item: " + s[0]);
for(int i = 1; i < s.length; i++) {
System.out.print(", " + s[i]);
}
System.out.println("");
}
This way you're accessing each string in the array instead of the array itself.
Hope this helps!
If you want to stay with underscore so your predicate function can be more flexible, here are 2 ideas.
Since the predicate for _.find
receives both the value and index of an element, you can use side effect to retrieve the index, like this:
var idx;
_.find(tv, function(voteItem, voteIdx){
if(voteItem.id == voteID){ idx = voteIdx; return true;};
});
Looking at underscore source, this is how _.find
is implemented:
_.find = _.detect = function(obj, predicate, context) {
var result;
any(obj, function(value, index, list) {
if (predicate.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
To make this a findIndex
function, simply replace the line result = value;
with result = index;
This is the same idea as the first method. I included it to point out that underscore uses side effect to implement _.find
as well.
The first way would be preferred to the second.
This is because the header file will show that the parameter is optional and what its default value will be. Additionally, this will ensure that the default value will be the same, no matter the implementation of the corresponding .cpp file.
In the second way, there is no guarantee of a default value for the second parameter. The default value could change, depending on how the corresponding .cpp file is implemented.
You might try passing actual types instead of strings.
import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = [datetime, datetime, str, float]
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
But it's going to be really hard to diagnose this without any of your data to tinker with.
And really, you probably want pandas to parse the the dates into TimeStamps, so that might be:
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=True)
One of the below solve your problem
URL::previous()
URL::back()
other
URL::current()
I believe the admin button will open the default configuration always. It simply contains a link to localhost/xampp
and it doesn't read the server configuration.
If you change the default settings, you know what you changed and you can enter the URL directly in the browser.
If you want a (almost) one-liner:
from collections import deque d = {} deque((d.setdefault(year, []).append(value) for year, value in source_of_data), maxlen=0)
Using dict.setdefault
, you can encapsulate the idea of "check if the key already exists and make a new list if not" into a single call. This allows you to write a generator expression which is consumed by deque
as efficiently as possible since the queue length is set to zero. The deque will be discarded immediately and the result will be in d
.
This is something I just did for fun. I don't recommend using it. There is a time and a place to consume arbitrary iterables through a deque, and this is definitely not it.
You can do this with this code also.
public class WriteSDCard extends Activity {
private static final String TAG = "MEDIA";
private TextView tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
checkExternalMedia();
writeToSDFile();
readRaw();
}
/** Method to check whether external media available and writable. This is adapted from
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */
private void checkExternalMedia(){
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
tv.append("\n\nExternal Media: readable="
+mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
}
/** Method to write ascii text characters to file on SD card. Note that you must add a
WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
a FileNotFound Exception because you won't have write permission. */
private void writeToSDFile(){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: "+root);
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to "+file);
}
/** Method to read in a text file placed in the res/raw directory of the application. The
method reads in all lines of the file sequentially. */
private void readRaw(){
tv.append("\nData read from res/raw/textfile.txt:");
InputStream is = this.getResources().openRawResource(R.raw.textfile);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr, 8192); // 2nd arg is buffer size
// More efficient (less readable) implementation of above is the composite expression
/*BufferedReader br = new BufferedReader(new InputStreamReader(
this.getResources().openRawResource(R.raw.textfile)), 8192);*/
try {
String test;
while (true){
test = br.readLine();
// readLine() returns null if no more lines in the file
if(test == null) break;
tv.append("\n"+" "+test);
}
isr.close();
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nThat is all");
}
}
I have a suspicion that this is related to the parser that BS will use to read the HTML. They document is here, but if you're like me (on OSX) you might be stuck with something that requires a bit of work:
You'll notice that in the BS4 documentation page above, they point out that by default BS4 will use the Python built-in HTML parser. Assuming you are in OSX, the Apple-bundled version of Python is 2.7.2 which is not lenient for character formatting. I hit this same problem, so I upgraded my version of Python to work around it. Doing this in a virtualenv will minimize disruption to other projects.
If doing that sounds like a pain, you can switch over to the LXML parser:
pip install lxml
And then try:
soup = BeautifulSoup(html, "lxml")
Depending on your scenario, that might be good enough. I found this annoying enough to warrant upgrading my version of Python. Using virtualenv, you can migrate your packages fairly easily.
To display the item number on the repeater you can use the Container.ItemIndex
property.
<asp:repeater id="rptRepeater" runat="server">
<itemtemplate>
Item <%# Container.ItemIndex + 1 %>| <%# Eval("Column1") %>
</itemtemplate>
<separatortemplate>
<br />
</separatortemplate>
</asp:repeater>
In jQuery you can do like this.
function random_no(){_x000D_
var ran=Math.random();_x000D_
jQuery('#random_no_container').html(ran);_x000D_
}_x000D_
_x000D_
window.setInterval(function(){_x000D_
/// call your function here_x000D_
random_no();_x000D_
}, 6000); // Change Interval here to test. For eg: 5000 for 5 sec
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="random_no_container">_x000D_
Hello. Here you can see random numbers after every 6 sec_x000D_
</div>
_x000D_
CSS (or jQuery, for that matter) can't animate between display: none;
and display: block;
. Worse yet: it can't animate between height: 0
and height: auto
. So you need to hard code the height (if you can't hard code the values then you need to use javascript, but this is an entirely different question);
#main-image{
height: 0;
overflow: hidden;
background: red;
-prefix-animation: slide 1s ease 3.5s forwards;
}
@-prefix-keyframes slide {
from {height: 0;}
to {height: 300px;}
}
You mention that you're using Animate.css, which I'm not familiar with, so this is a vanilla CSS.
You can see a demo here: http://jsfiddle.net/duopixel/qD5XX/
Make sure you import the @Test
annotation from the correct library:
import org.junit.jupiter.api.Test
not
import org.junit.Test
If you are getting error like
Try removing the above file manually(Careful). Git will merge this file from master branch.
If you've installed the WIF SDK, try :
C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5\
Microsoft.IdentityModel.dll
You can also get the same issue if your class doesn't contain any public methods/properties. I normally have dedicated DTOs for API requests and responses, declared public, but forgot in one case to make the methods public as well - which caused the "empty" bean in the first place.
A = zeros(20, 10, 3); %# Creates a 20x10x3 matrix
B = zeros(4,4);
C = zeros(size(B,1), size(B,2), 4); %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B; %# Copy the content of B into C's first set of values
zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0
for a 3D matrix. To confirm the size of your matrices you can run: size(A)
which gives 20 10 3
.
There is no explicit bound on the number of dimensions a matrix may have.
Please note that both the HTML5 specification of W3C and WhatWG standardize
<link rel="icon" href="/favicon.ico">
Note the value of the "rel" attribute!
The value shortcut icon
for the rel
attribute is a very old Internet Explorer specific extension and deprecated.
So please consider not using it any more and updating your files so they are standards compliant and are displayed correctly in all browsers.
You might also want to take a look at this great post: rel="shortcut icon" considered harmful
I was having the same issue, I made the table fixed and then specified my td width. If you have th you can do those as well.
<style>
table {
table-layout: fixed;
word-wrap: break-word;
}
</style>
<td width="10%" /td>
I didn't have any luck with .table-nonfluid.
To export data to csv/excel from Kibana follow the following steps:-
Click on Visualize Tab & select a visualization (if created). If not created create a visualziation.
Click on caret symbol (^) which is present at the bottom of the visualization.
Then you will get an option of Export:Raw Formatted as the bottom of the page.
Please find below attached image showing Export option after clicking on caret symbol.
It works too :
<form>
<label for="male"><input type="checkbox" name="male" id="male" />Male</label><br />
<label for="female"><input type="checkbox" name="female" id="female" />Female</label>
</form>
Convert each character to its ASCII code, subtract the ASCII code for "a" and add 1. I'm deliberately leaving the code as an exercise.
This sounds like homework. If so, please tag it as such.
Also, this won't deal with upper case letters, since you didn't state any requirement to handle them, but if you need to then just lowercase the string before you start.
Oh, and this will only deal with the latin "a" through "z" characters without any accents, etc.
Facebook is using LAMP structure. Facebook’s back-end services are written in a variety of different programming languages including C++, Java, Python, and Erlang and they are used according to requirement. With LAMP Facebook uses some technologies ,to support large number of requests, like
Memcache - It is a memory caching system that is used to speed up dynamic database-driven websites (like Facebook) by caching data and objects in RAM to reduce reading time. Memcache is Facebook’s primary form of caching and helps alleviate the database load. Having a caching system allows Facebook to be as fast as it is at recalling your data.
Thrift (protocol) - It is a lightweight remote procedure call framework for scalable cross-language services development. Thrift supports C++, PHP, Python, Perl, Java, Ruby, Erlang, and others.
Cassandra (database) - It is a database management system designed to handle large amounts of data spread out across many servers.
HipHop for PHP - It is a source code transformer for PHP script code and was created to save server resources. HipHop transforms PHP source code into optimized C++. After doing this, it uses g++ to compile it to machine code.
If we go into more detail, then answer to this question go longer. We can understand more from following posts:
Well, since you are using Python, you can just open a file and keep reading lines from it.
f = open('file.log')
If the line read is not empty, you process it.
line = f.readline()
if line:
// Do what you want with the line
You may be missing that it is ok to keep calling readline
at the EOF. It will just keep returning an empty string in this case. And when something is appended to the log file, the reading will continue from where it stopped, as you need.
If you are looking for a solution that uses events, or a particular library, please specify this in your question. Otherwise, I think this solution is just fine.
I had the same problem, by accident mistake. I'll share it here, in case someone may have made the same mistake.
Basic steps, as others described.
Good luck!
This works like a charm, fast and accurate:
function replace_string_in_file($filename, $string_to_replace, $replace_with){
$content=file_get_contents($filename);
$content_chunks=explode($string_to_replace, $content);
$content=implode($replace_with, $content_chunks);
file_put_contents($filename, $content);
}
Usage:
$filename="users/data/letter.txt";
$string_to_replace="US$";
$replace_with="Yuan";
replace_string_in_file($filename, $string_to_replace, $replace_with);
// never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool
We have experienced the same issue when moving the sql server in-house.
A good solution that we ended up using is splitting the sql file into chunks. There are several ways to do that. Use
http://www.ozerov.de/bigdump/ seems good (but never used it)
http://www.rusiczki.net/2007/01/24/sql-dump-file-splitter/ used it and it was very useful to get structure out of the mess and you can take it from there.
Hope this helps :)
Look at the "Sprite Text" sample in the GLSurfaceView samples.
create schema tableName authorization dbo
go
IF OBJECT_ID ('tableName.put_fieldValue', 'P' ) IS NOT NULL
drop proc tableName.put_fieldValue
go
create proc tableName.put_fieldValue(@fieldValue int) as
declare @tableid int = 0
select @tableid = tableid from table where fieldValue=''
if @tableid = 0 begin
insert into table(fieldValue) values('')
select @tableid = scope_identity()
end
return @tableid
go
declare @tablid int = 0
exec @tableid = tableName.put_fieldValue('')
You can use os.walk()
to recursively iterate through a directory and all its subdirectories:
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith((".html", ".htm")):
# whatever
To build a list of these names, you can use a list comprehension:
htmlfiles = [os.path.join(root, name)
for root, dirs, files in os.walk(path)
for name in files
if name.endswith((".html", ".htm"))]
There are multiple ways to achieve this:
--simulator
flag--udid
flagFirstly you need to list all the available devices. To list all the devices run
xcrun simctl list device
This will give output as follows:
These are the available devices for iOS 13.0 onwards:
== Devices ==
-- iOS 13.6 --
iPhone 8 (5C7EF61D-6080-4065-9C6C-B213634408F2) (Shutdown)
iPhone 8 Plus (5A694E28-EF4D-4CDD-85DD-640764CAA25B) (Shutdown)
iPhone 11 (D6820D3A-875F-4CE0-B907-DAA060F60440) (Shutdown)
iPhone 11 Pro (B452E7A1-F21C-430E-98F0-B02F0C1065E1) (Shutdown)
iPhone 11 Pro Max (94973B5E-D986-44B1-8A80-116D1C54665B) (Shutdown)
iPhone SE (2nd generation) (90953319-BF9A-4C6E-8AB1-594394AD26CE) (Booted)
iPad Pro (9.7-inch) (9247BC07-00DB-4673-A353-46184F0B244E) (Shutdown)
iPad (7th generation) (3D5B855D-9093-453B-81EB-B45B7DBF0ADF) (Shutdown)
iPad Pro (11-inch) (2nd generation) (B3AA4C36-BFB9-4ED8-BF5A-E37CA38394F8) (Shutdown)
iPad Pro (12.9-inch) (4th generation) (DBC7B524-9C75-4C61-A568-B94DA0A9BCC4) (Shutdown)
iPad Air (3rd generation) (03E3FE18-AB46-481E-80A0-D37383ADCC2C) (Shutdown)
-- tvOS 13.4 --
Apple TV (41579EEC-0E68-4D36-9F98-5822CD1A4104) (Shutdown)
Apple TV 4K (B168EF40-F2A4-4A91-B4B0-1F541201479B) (Shutdown)
Apple TV 4K (at 1080p) (D55F9086-A56E-4893-ACAD-579FB63C561E) (Shutdown)
-- watchOS 6.2 --
Apple Watch Series 4 - 40mm (D4BA8A57-F9C1-4F55-B3E0-6042BA7C4ED4) (Shutdown)
Apple Watch Series 4 - 44mm (65D5593D-29B9-42CD-9417-FFDBAE9AED87) (Shutdown)
Apple Watch Series 5 - 40mm (1B73F8CC-9ECB-4018-A212-EED508A68AE3) (Shutdown)
Apple Watch Series 5 - 44mm (5922489B-5CF9-42CD-ACB0-B11FAF88562F) (Shutdown)
Then from the output you can select the name or the uuid then proceed as you wish.
--simulator
run:npx react-native run-ios --simulator="iPhone SE"
--udid
flag run:npx react-native run-ios --udid 90953319-BF9A-4C6E-8AB1-594394AD26CE
I hope this answer helped you.
function yourfunctionName() {
var yourFileName = $("#yourinputfieldis").val();
var yourFileExtension = yourFileName .replace(/^.*\./, '');
switch (yourFileExtension ) {
case 'pdf':
case 'jpg':
case 'doc':
$("#formId").submit();// your condition what you want to do
break;
default:
alert('your File extension is wrong.');
this.value = '';
}
}
From answer that was removed due to being written in Spanish:
All of the above fixes may not work in android studio. If you are using ANDROID STUDIO please use the following fix.
Use
xmlns: compat = "http://schemas.android.com/tools"
on the menu label instead of
xmlns: compat = "http://schemas.android.com/apk/res-auto"
To complete Zachary's answer, here is a workaround for the "extend in overrides" limitation of eslint config :
overrides: [
Object.assign(
{
files: [ '**/*.test.js' ],
env: { jest: true },
plugins: [ 'jest' ],
},
require('eslint-plugin-jest').configs.recommended
)
]
From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724
One more difference specific to microsoft sql server is with delete
you can use output
statement to track what records have been deleted, e.g.:
delete from [SomeTable]
output deleted.Id, deleted.Name
You cannot do this with truncate
.
As stated by Harry Joy, you can do it on the onclick
attr like so:
<input type="button" onclick="func1();func2();" value="Call2Functions" />
Or, in your JS like so:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1();
func2();
};
Or, if you are assigning an onclick programmatically, and aren't sure if a previous onclick existed (and don't want to overwrite it):
var Call2FunctionsEle = document.getElementById( 'Call2Functions' ),
func1 = Call2FunctionsEle.onclick;
Call2FunctionsEle.onclick = function()
{
if( typeof func1 === 'function' )
{
func1();
}
func2();
};
If you need the functions run in scope of the element which was clicked, a simple use of apply could be made:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1.apply( this, arguments );
func2.apply( this, arguments );
};
I have come up with a slighly different approach that should work on cross platforms
http://www.jqui.net/tips-tricks/fixing-the-auto-scale-on-mobile-devices/
So far I have tested in on
Samsun galaxy 2
iPhone 4
@media screen and (max-width:800px) {
This is a massive lip forward with mobile development ...
Using CSS, of course...
label { display: block; width: 100px; }
The width
attribute is deprecated, and CSS should always be used to control these kinds of presentational styles.
The angular.forEach
loop can't break on a condition match.
My personal advice is to use a NATIVE FOR loop instead of angular.forEach
.
The NATIVE FOR loop is around 90% faster then other for loops.
USE FOR loop IN ANGULAR:
var numbers = [0, 1, 2, 3, 4, 5];
for (var i = 0, len = numbers.length; i < len; i++) {
if (numbers[i] === 1) {
console.log('Loop is going to break.');
break;
}
console.log('Loop will continue.');
}
Note the ""
at the beginning and at the end!
Run a program and pass a Long Filename
cmd /c write.exe "c:\sample documents\sample.txt"
Spaces in Program Path
cmd /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in Program Path + parameters
cmd /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
Spaces in Program Path + parameters with spaces
cmd /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch Demo1 and then Launch Demo2
cmd /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
mvn install primary jobs are to 1)Download The Dependencies and 2)Build The Project
while job 1 is nowadays taken care by IDs like intellij (they download for any dependency at POM)
mvn install is majorly now used for job 2.
If Multiset
extends from the Array
class
x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]
x.union(y) # => [1, 2, 4, 7] (ONLY IN RUBY 2.6)
x.union(y, z) # => [1, 2, 4, 7, 3] (ONLY IN RUBY 2.6)
x | y # => [1, 2, 4, 7]
x.difference(y) # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z) # => [4] (ONLY IN RUBY 2.6)
x - y # => [4, 7]
x & y # => [1, 2]
For more info about the new methods in Ruby 2.6, you can check this blog post about its new features
From within your batch file:
%cd%
refers to the current working directory (variable)%~dp0
refers to the full path to the batch file's directory (static)%~dpnx0
and %~f0
both refer to the full path to the batch directory and file name (static).CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
proc_label:BEGIN
IF tablename IS NULL THEN
LEAVE proc_label;
END IF;
#proceed the code
END;
use this actiion
$(document).ready(function () {
var a = this.id;
alert (a);
});
Using git 2.9 (precisely 2.9.2.windows.1)
git reset HEAD^
prompts for more; not sure what is expected input here. Please refer below screenshot
Found other solution git reset HEAD~#numberOfCommits
using which we can choose to select number of local commits you want to reset by keeping your changes intact. Hence, we get an opportunity to throw away all local commits as well as limited number of local commits.
There isn't one built in but you could write your own quite easily:
(function($) {
$.fn.invisible = function() {
return this.each(function() {
$(this).css("visibility", "hidden");
});
};
$.fn.visible = function() {
return this.each(function() {
$(this).css("visibility", "visible");
});
};
}(jQuery));
You can then call this like so:
$("#someElem").invisible();
$("#someOther").visible();
Here's a working example.
LumiSoft.ee - works great, fairly easy. Compiles with .NET 4.0.
Here are the required links to their lib and examples. Downloads Main:
http://www.lumisoft.ee/lsWWW/Download/Downloads/
Code Examples:
are located here: ...lsWWW/Download/Downloads/Examples/
.NET:
are located here: ...lsWWW/Download/Downloads/Net/
I am putting a SIMPLE sample up using their lib on codeplex (IMAPClientLumiSoft.codeplex.com). You must get their libraries directly from their site. I am not including them because I don't maintain their code nor do I have any rights to the code. Go to the links above and download it directly. I set LumiSoft project properties in my VS2010 to build all of it in .NET 4.0 which it did with no errors. Their samples are fairly complex and maybe even overly tight coding when just an example. Although I expect that these are aimed at advanced level developers in general.
Their project worked with minor tweaks. The tweaks: Their IMAP Client Winform example is set in the project properties as "Release" which prevents VS from breaking on debug points. You must use the solution "Configuration Manager" to set the project to "Active(Debug)" for breakpoints to work. Their examples use anonymous methods for event handlers which is great tight coding... not real good as a teaching tool. My project uses "named" event method handlers so you can set breakpoints inside the handlers. However theirs is an excellent way to handle inline code. They might have used the newer Lambda methods available since .NET 3.0 but did not and I didn't try to convert them.
From their samples I simplified the IMAP client to bare minimum.
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
size = models.IntegerField(validators=[MinValueValidator(0),
MaxValueValidator(5)])
How about using the Dynamic data template that comes with Visual Studio. This could be hosted on IIS.
Option 1
You didn't say much about your environment, but assuming you have it available you could use a PowerShell script; one example is here. The essence of this is:
$smtp = New-Object Net.Mail.SmtpClient("ho-ex2010-caht1.exchangeserverpro.net")
$smtp.Send("[email protected]","[email protected]","Test Email","This is a test")
You could then launch the script from the command line as per this example:
powershell.exe -noexit c:\scripts\test.ps1
Note that PowerShell 2.0, which is installed by default on Windows 7 and Windows Server 2008R2, includes a simpler Send-MailMessage
command, making things easier.
Option 2
If you're prepared to use third-party software, is something line this SendEmail command-line tool. It depends on your target environment, though; if you're deploying your batch file to multiple machines, that will obviously require inclusion (but not formal installation) each time.
Option 3
You could drive Outlook directly from a VBA script, which in turn you would trigger from a batch file; this would let you send an email using Outlook itself, which looks to be closest to what you're wanting. There are two parts to this; first, figure out the VBA scripting required to send an email. There are lots of examples for this online, including from Microsoft here. Essence of this is:
Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Set objOutlook = CreateObject("Outlook.Application")
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
With objOutlookMsg
Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
objOutlookRecip.Type = olTo
' Set the Subject, Body, and Importance of the message.
.Subject = "This is an Automation test with Microsoft Outlook"
.Body = "This is the body of the message." &vbCrLf & vbCrLf
.Importance = olImportanceHigh 'High importance
If Not IsMissing(AttachmentPath) Then
Set objOutlookAttach = .Attachments.Add(AttachmentPath)
End If
For Each ObjOutlookRecip In .Recipients
objOutlookRecip.Resolve
Next
.Save
.Send
End With
Set objOutlook = Nothing
End Sub
Then, launch Outlook from the command line with the /autorun
parameter, as per this answer (alter path/macroname as necessary):
C:\Program Files\Microsoft Office\Office11\Outlook.exe" /autorun macroname
Option 4
You could use the same approach as option 3, but move the Outlook VBA into a PowerShell script (which you would run from a command line). Example here. This is probably the tidiest solution, IMO.
Most answers are too wordy.
splice
andslice
return rest of elements in the array.splice
mutates the array being operated with elements removed whileslice
not.
Initiate the NodeList inside the for loop and you will get the desired output.
ArrayList<String> nodes = new ArrayList<String>();
ArrayList list=new ArrayList();
for(int i=0;i<PropertyNode.getLength()-1;i++){
ArrayList NodeList=new ArrayList();
Node childNode = PropertyNode.item(i);
NodeList Children = childNode.getChildNodes();
if(Children!=null){
nodes.clear();
nodes.add("PropertyStart");
nodes.add(Children.item(3).getTextContent());
nodes.add(Children.item(7).getTextContent());
nodes.add(Children.item(9).getTextContent());
nodes.add(Children.item(11).getTextContent());
nodes.add(Children.item(13).getTextContent());
nodes.add("PropertyEnd");
}
NodeList.addAll(nodes);
list.add(NodeList);
}
Explanation: NodeList is an object which remains same throughout the loop so adding same variable to list in a loop will actually add it only once. The loop is only adding its variables in single NodeList array hence you must be seeing
[/*list*/ [ /*NodeList*/ ] ]
and NodeList contains [prostart, a,b,c,proend,prostart,d,e,f,proend ...]
You want rows where that condition is true so you need a comma:
data[data$Ozone > 14, ]
For those who came here looking for "how to get All input of POST" only
class Illuminate\Http\Request
extends from Symfony\Component\HttpFoundation\Request
which has two class variables that store request parameters.
public $query
- for GET parameters
public $request
- for POST parameters
Usage: To get a post data only
$request = Request::instance();
$request->request->all(); //Get all post requests
$request->request->get('my_param'); //Get a post parameter
Source here
EDIT
For Laravel >= 5.5, you can simply call $request->post()
or $request->post('my_param')
which internally calls $request->request->all()
or $request->request->get('my_param')
respectively.
From C++ Primer:
The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.
I come across some cases where it is both convenient and concise to use stringstream.
It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.
Suppose a
and b
are complex numbers expressed in string format, we want to get the result of multiplication of a
and b
also in string format. The code is as follows:
string a = "1+2i", b = "1+3i";
istringstream sa(a), sb(b);
ostringstream out;
int ra, ia, rb, ib;
char buff;
// only read integer values to get the real and imaginary part of
// of the original complex number
sa >> ra >> buff >> ia >> buff;
sb >> rb >> buff >> ib >> buff;
out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';
// final result in string format
string result = out.str()
It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:
string simplifyPath(string path) {
string res, tmp;
vector<string> stk;
stringstream ss(path);
while(getline(ss,tmp,'/')) {
if (tmp == "" or tmp == ".") continue;
if (tmp == ".." and !stk.empty()) stk.pop_back();
else if (tmp != "..") stk.push_back(tmp);
}
for(auto str : stk) res += "/"+str;
return res.empty() ? "/" : res;
}
Without the use of stringstream, it would be difficult to write such concise code.
It depends on what you're looking for.
With adjacency matrices you can answer fast to questions regarding if a specific edge between two vertices belongs to the graph, and you can also have quick insertions and deletions of edges. The downside is that you have to use excessive space, especially for graphs with many vertices, which is very inefficient especially if your graph is sparse.
On the other hand, with adjacency lists it is harder to check whether a given edge is in a graph, because you have to search through the appropriate list to find the edge, but they are more space efficient.
Generally though, adjacency lists are the right data structure for most applications of graphs.
Declare a Flask endpoint to accept POST input type and then do necessary steps. Use jQuery to post the data.
from flask import request
@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data(data):
if request.method == "POST":
#perform action here
var value = $('.textbox').val();
$.ajax({
type: 'POST',
url: "{{ url_for('parse_data') }}",
data: JSON.stringify(value),
contentType: 'application/json',
success: function(data){
// do something with the received data
}
});
It might also be worth mentioning that inline will try to open Office Documents (xls, doc etc) directly from the server, which might lead to a User Credentials Prompt.
see this link:
http://forums.asp.net/t/1885657.aspx/1?Access+the+SSRS+Report+in+excel+format+on+server
somebody tried to deliver an Excel Report from SSRS via ASP.Net -> the user always got prompted to enter the credentials. After clicking cancel on the prompt it would be opened anyway...
If the Content Disposition is marked as Attachment it will automatically be saved to the temp folder after clicking open and then opened in Excel from the local copy.
var standardsList = [
{"Grade": "Math K", "Domain": "Counting & Cardinality"},
{"Grade": "Math K", "Domain": "Counting & Cardinality"},
{"Grade": "Math K", "Domain": "Counting & Cardinality"},
{"Grade": "Math K", "Domain": "Counting & Cardinality"},
{"Grade": "Math K", "Domain": "Geometry"},
{"Grade": "Math 1", "Domain": "Counting & Cardinality"},
{"Grade": "Math 1", "Domain": "Counting & Cardinality"},
{"Grade": "Math 1", "Domain": "Orders of Operation"},
{"Grade": "Math 2", "Domain": "Geometry"},
{"Grade": "Math 2", "Domain": "Geometry"}
];
function uniqurArray(array){
var a = array.concat();
for(var i=0; i<a.length; i++) {
for(var j=i+1; j<a.length; j++) {
if(a[i].Grade === a[j].Grade){
a.splice(j--, 1);
}
}
}
return a;
}
uniqurArray(standardsList) // put this js in console and you get uniq object in array
You can use Sorted Set in redis to get a TTL container with timestamp as score.
For example, whenever you insert a event string into the set you can set its score to the event time.
Thus you can get data of any time window by calling
zrangebyscore "your set name" min-time max-time
Moreover, we can do expire by using zremrangebyscore "your set name" min-time max-time
to remove old events.
The only drawback here is you have to do housekeeping from an outsider process to maintain the size of the set.
Include org.json.jsonobject
in your project.
You can then do this:
JSONObject jresponse = new JSONObject(responseString);
responseString = jresponse.getString("NeededString");
Assuming, responseString
holds the response you receive.
If you need to know how to convert the received response to a String, here's how to do it:
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();
Your .vimrc
file goes in your $HOME
directory. In *nix, cd ~; vim .vimrc
. The commands in the .vimrc
are the same as you type in ex-mode in vim, only without the leading colon, so colo evening
would suffice. Comments in the .vimrc
are indicated with a leading double-quote.
To see an example vimrc, open $VIMRUNTIME/vimrc_example.vim
from within vim
:e $VIMRUNTIME/vimrc_example.vim
This is how I did this so that only one progress dialog can be open at a time. Based off of the answer from Suraj Bajaj
private ProgressDialog progress;
public void showLoadingDialog() {
if (progress == null) {
progress = new ProgressDialog(this);
progress.setTitle(getString(R.string.loading_title));
progress.setMessage(getString(R.string.loading_message));
}
progress.show();
}
public void dismissLoadingDialog() {
if (progress != null && progress.isShowing()) {
progress.dismiss();
}
}
I also had to use
protected void onResume() {
dismissLoadingDialog();
super.onResume();
}
In the comments of http://www.php.net/manual/de/function.mysql-db-name.php I found this one from ericpp % bigfoot.com:
If you just need the current database name, you can use MySQL's SELECT DATABASE() command:
<?php
function mysql_current_db() {
$r = mysql_query("SELECT DATABASE()") or die(mysql_error());
return mysql_result($r,0);
}
?>
From Microsoft's Website:
.NET Core refers to several technologies including .NET Core, ASP.NET Core and Entity Framework Core.
These technologies are different than native .NET in that they run using CoreCLR runtime (used in the Universal Windows Platform).
As you mentioned in your question, .NET Core is not only open-source, but portable as well [runs on MacOS, Windows, and Linux]
The internals of .NET Core are also optimised to not use different modules from its core library unless it is required by the application.
you can try using this
System.Web.HttpContext.Current.Server.MapPath(path);
or use HostingEnvironment.MapPath
System.Web.Hosting.HostingEnvironment.MapPath(path);
So, here is an example of the dateutil.relativedelta
which I found useful for iterating through the past year, skipping a month each time to the present date:
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> today = datetime.datetime.today()
>>> month_count = 0
>>> while month_count < 12:
... day = today - relativedelta(months=month_count)
... print day
... month_count += 1
...
2010-07-07 10:51:45.187968
2010-06-07 10:51:45.187968
2010-05-07 10:51:45.187968
2010-04-07 10:51:45.187968
2010-03-07 10:51:45.187968
2010-02-07 10:51:45.187968
2010-01-07 10:51:45.187968
2009-12-07 10:51:45.187968
2009-11-07 10:51:45.187968
2009-10-07 10:51:45.187968
2009-09-07 10:51:45.187968
2009-08-07 10:51:45.187968
As with the other answers, you have to figure out what you actually mean by "6 months from now." If you mean "today's day of the month in the month six years in the future" then this would do:
datetime.datetime.now() + relativedelta(months=6)
Edited answer: IE understands just screen and print as import media. All other CSS supplied along with the import statement causes IE8 to ignore the import statement. Geco browser like safari or mozilla didn't have this problem.
you can use String format to include variables within strings
i use this code to include 2 variable in string:
String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);
You could use a semaphore.
While the condition is not met, another thread acquires the semaphore.
Your thread would try to acquire it with acquireUninterruptibly()
or tryAcquire(int permits, long timeout, TimeUnit unit)
and would be blocked.
When the condition is met, the semaphore is also released and your thread would acquire it.
You could also try using a SynchronousQueue
or a CountDownLatch
.
You could use a recursive scalar function:-
set nocount on
create table location (
id int,
name varchar(50),
parent int
)
insert into location values
(1,'france',null),
(2,'paris',1),
(3,'belleville',2),
(4,'lyon',1),
(5,'vaise',4),
(6,'united kingdom',null),
(7,'england',6),
(8,'manchester',7),
(9,'fallowfield',8),
(10,'withington',8)
go
create function dbo.breadcrumb(@child int)
returns varchar(1024)
as begin
declare @returnValue varchar(1024)=''
declare @parent int
select @returnValue+=' > '+name,@parent=parent
from location
where id=@child
if @parent is not null
set @returnValue=dbo.breadcrumb(@parent)+@returnValue
return @returnValue
end
go
declare @location int=1
while @location<=10 begin
print dbo.breadcrumb(@location)+' >'
set @location+=1
end
produces:-
> france >
> france > paris >
> france > paris > belleville >
> france > lyon >
> france > lyon > vaise >
> united kingdom >
> united kingdom > england >
> united kingdom > england > manchester >
> united kingdom > england > manchester > fallowfield >
> united kingdom > england > manchester > withington >
@MykolaGolubyev has already given wonderful explanation. I was looking for a solution to do somthing like this MyClass obj ( MyAnotherClass() )
but the compiler was interpreting it as a function declaration.
C++11 has braced-init-list. Using this we can do something like this
Temp t{String()};
However, this:
Temp t(String());
throws compilation error as it considers t
as of type Temp(String (*)())
.
#include <iostream>
class String {
public:
String(const char* str): ptr(str)
{
std::cout << "Constructor: " << str << std::endl;
}
String(void): ptr(nullptr)
{
std::cout << "Constructor" << std::endl;
}
virtual ~String(void)
{
std::cout << "Destructor" << std::endl;
}
private:
const char *ptr;
};
class Temp {
public:
Temp(String in): str(in)
{
std::cout << "Temp Constructor" << std::endl;
}
Temp(): str(String("hello"))
{
std::cout << "Temp Constructor: 2" << std::endl;
}
virtual ~Temp(void)
{
std::cout << "Temp Destructor" << std::endl;
}
virtual String get_str()
{
return str;
}
private:
String str;
};
int main(void)
{
Temp t{String()}; // Compiles Success!
// Temp t(String()); // Doesn't compile. Considers "t" as of type: Temp(String (*)())
t.get_str(); // dummy statement just to check if we are able to access the member
return 0;
}
matrix multiplication, see the following example:
> A <- matrix (c(1,3,4, 5,8,9, 1,3,3), 3,3)
> A
[,1] [,2] [,3]
[1,] 1 5 1
[2,] 3 8 3
[3,] 4 9 3
>
> B <- matrix (c(2,4,5, 8,9,2, 3,4,5), 3,3)
>
> B
[,1] [,2] [,3]
[1,] 2 8 3
[2,] 4 9 4
[3,] 5 2 5
>
>
> A %*% B
[,1] [,2] [,3]
[1,] 27 55 28
[2,] 53 102 56
[3,] 59 119 63
> B %*% A
[,1] [,2] [,3]
[1,] 38 101 35
[2,] 47 128 43
[3,] 31 86 26
Also see:
http://en.wikipedia.org/wiki/Matrix_multiplication
If this does not follow the size of matrix rule you will get the error:
> A <- matrix(c(1,2,3,4,5,6), 3,2)
> A
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> B <- matrix (c(3,1,3,4,4,4,4,4,3), 3,3)
> B
[,1] [,2] [,3]
[1,] 3 4 4
[2,] 1 4 4
[3,] 3 4 3
> A%*%B
Error in A %*% B : non-conformable arguments
As a db driver, there is also oursql. Some of the reasons listed on that link, which say why oursql is better:
- oursql has real parameterization, sending the SQL and data to MySQL completely separately.
- oursql allows text or binary data to be streamed into the database and streamed out of the database, instead of requiring everything to be buffered in the client.
- oursql can both insert rows lazily and fetch rows lazily.
- oursql has unicode support on by default.
- oursql supports python 2.4 through 2.7 without any deprecation warnings on 2.6+ (see PEP 218) and without completely failing on 2.7 (see PEP 328).
- oursql runs natively on python 3.x.
Very similar to mysqldb:
import oursql
db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name')
cur=db_connection.cursor()
cur.execute("SELECT * FROM `tbl_name`")
for row in cur.fetchall():
print row[0]
The tutorial in the documentation is pretty decent.
And of course for ORM SQLAlchemy is a good choice, as already mentioned in the other answers.
You can also use LocalDate.parse()
or LocalDateTime.parse()
on a String
without providing it with a pattern, if the String
is in ISO-8601 format.
for example,
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
System.out.println("Date: " + aLD);
String strDatewithTime = "2015-08-04T10:11:30";
LocalDateTime aLDT = LocalDateTime.parse(strDatewithTime);
System.out.println("Date with Time: " + aLDT);
Output,
Date: 2015-08-04
Date with Time: 2015-08-04T10:11:30
and use DateTimeFormatter
only if you have to deal with other date patterns.
For instance, in the following example, dd MMM uuuu represents the day of the month (two digits), three letters of the name of the month (Jan, Feb, Mar,...), and a four-digit year:
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
String anotherDate = "04 Aug 2015";
LocalDate lds = LocalDate.parse(anotherDate, dTF);
System.out.println(anotherDate + " parses to " + lds);
Output
04 Aug 2015 parses to 2015-08-04
also remember that the DateTimeFormatter
object is bidirectional; it can both parse input and format output.
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
System.out.println(aLD + " formats as " + dTF.format(aLD));
Output
2015-08-04 formats as 04 Aug 2015
(see complete list of Patterns for Formatting and Parsing DateFormatter)
Symbol Meaning Presentation Examples
------ ------- ------------ -------
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
D day-of-year number 189
M/L month-of-year number/text 7; 07; Jul; July; J
d day-of-month number 10
Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
Y week-based-year year 1996; 96
w week-of-week-based-year number 27
W week-of-month number 4
E day-of-week text Tue; Tuesday; T
e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
F week-of-month number 3
a am-pm-of-day text PM
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-am-pm (1-24) number 0
H hour-of-day (0-23) number 0
m minute-of-hour number 30
s second-of-minute number 55
S fraction-of-second fraction 978
A milli-of-day number 1234
n nano-of-second number 987654321
N nano-of-day number 1234000000
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;
p pad next pad modifier 1
' escape for text delimiter
'' single quote literal '
[ optional section start
] optional section end
# reserved for future use
{ reserved for future use
} reserved for future use
Procedure from Jake https://stackoverflow.com/a/6476091/6751901 is very simple and good solution for adding new columns, but with one additional line:
DROP PROCEDURE IF EXISTS foo;;
you can add new columns later there, and it will work next time too:
delimiter ;;
DROP PROCEDURE IF EXISTS foo;;
create procedure foo ()
begin
declare continue handler for 1060 begin end;
alter table atable add subscriber_surname varchar(64);
alter table atable add subscriber_address varchar(254);
end;;
call foo();;
if result is None:
print "error parsing stream"
elif result:
print "result pass"
else:
print "result fail"
keep it simple and explicit. You can of course pre-define a dictionary.
messages = {None: 'error', True: 'pass', False: 'fail'}
print messages[result]
If you plan on modifying your simulate
function to include more return codes, maintaining this code might become a bit of an issue.
The simulate
might also raise an exception on the parsing error, in which case you'd either would catch it here or let it propagate a level up and the printing bit would be reduced to a one-line if-else statement.
map.put(key, map.get(key) + 1);
should be fine. It will update the value for the existing mapping. Note that this uses auto-boxing. With the help of map.get(key)
we get the value of corresponding key, then you can update with your requirement. Here I am updating to increment value by 1.
Simply changing HTTP to HTTPS solved this issue for me.
WRONG :
<script src="http://code.jquery.com/jquery-3.5.1.js"></script>
CORRECT :
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
Regards to your question... counting one Field? I decided to make it a question, but I hope it helps...
Say I have the following DataFrame
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.normal(0, 1, (5, 2)), columns=["A", "B"])
You could count a single column by
df.A.count()
#or
df['A'].count()
both evaluate to 5.
The cool thing (or one of many w.r.t. pandas
) is that if you have NA
values, count takes that into consideration.
So if I did
df['A'][1::2] = np.NAN
df.count()
The result would be
A 3
B 5
You are looking to use dirname. If you only want that one directory, you can use os.path.basename,
When put all together it looks like this:
os.path.basename(os.path.dirname('dir/sub_dir/other_sub_dir/file_name.txt'))
That should get you "other_sub_dir"
The following is not the ideal approach, but I originally proposed,using os.path.split, and simply get the last item. which would look like this:
os.path.split(os.path.dirname('dir/sub_dir/other_sub_dir/file_name.txt'))[-1]
Anytime you're tempted to pass a collection (or pointer or reference to one) to a function, ask yourself whether you couldn't pass a couple of iterators instead. Chances are that by doing so, you'll make your function more versatile (e.g., make it trivial to work with data in another type of container when/if needed).
In this case, of course, there's not much point since the standard library already has perfectly good binary searching, but when/if you write something that's not already there, being able to use it on different types of containers is often quite handy.
This answer is similar to the accepted one, but a bit less convoluted.
L<-list()
for (i in 1:3) {
L<-c(L, list(list(sample(1:3))))
}
Java does not truely support multidimensional arrays. In Java, a two-dimensional array is simply an array of arrays, a three-dimensional array is an array of arrays of arrays, a four-dimensional array is an array of arrays of arrays of arrays, and so on...
We can define a two-dimensional array as:
int[ ] num[ ] = {{1,2}, {1,2}, {1,2}, {1,2}}
int[ ][ ] num = new int[4][2]
num[0][0] = 1;
num[0][1] = 2;
num[1][0] = 1;
num[1][1] = 2;
num[2][0] = 1;
num[2][1] = 2;
num[3][0] = 1;
num[3][1] = 2;
If you don't allocate, let's say num[2][1]
, it is not initialized and then it is automatically allocated 0, that is, automatically num[2][1] = 0
;
Below, num1.length
gives you rows.
While num1[0].length
gives you the number of elements related to num1[0]
. Here num1[0]
has related arrays num1[0][0]
and num[0][1]
only.
Here we used a for
loop which helps us to calculate num1[i].length
. Here i
is incremented through a loop.
class array
{
static int[][] add(int[][] num1,int[][] num2)
{
int[][] temp = new int[num1.length][num1[0].length];
for(int i = 0; i<temp.length; i++)
{
for(int j = 0; j<temp[i].length; j++)
{
temp[i][j] = num1[i][j]+num2[i][j];
}
}
return temp;
}
public static void main(String args[])
{
/* We can define a two-dimensional array as
1. int[] num[] = {{1,2},{1,2},{1,2},{1,2}}
2. int[][] num = new int[4][2]
num[0][0] = 1;
num[0][1] = 2;
num[1][0] = 1;
num[1][1] = 2;
num[2][0] = 1;
num[2][1] = 2;
num[3][0] = 1;
num[3][1] = 2;
If you don't allocate let's say num[2][1] is
not initialized, and then it is automatically
allocated 0, that is, automatically num[2][1] = 0;
3. Below num1.length gives you rows
4. While num1[0].length gives you number of elements
related to num1[0]. Here num1[0] has related arrays
num1[0][0] and num[0][1] only.
5. Here we used a 'for' loop which helps us to calculate
num1[i].length, and here i is incremented through a loop.
*/
int num1[][] = {{1,2},{1,2},{1,2},{1,2}};
int num2[][] = {{1,2},{1,2},{1,2},{1,2}};
int num3[][] = add(num1,num2);
for(int i = 0; i<num1.length; i++)
{
for(int j = 0; j<num1[j].length; j++)
System.out.println("num3[" + i + "][" + j + "]=" + num3[i][j]);
}
}
}
For a more general solution, for JAXB-XML serialization of any top level list , which only requires 1 new class to be written, check out the solution given in this question:
Is it possible to programmatically configure JAXB?
public class Wrapper<T> {
private List<T> items = new ArrayList<T>();
@XmlAnyElement(lax=true)
public List<T> getItems() {
return items;
}
}
//JAXBContext is thread safe and so create it in constructor or
//setter or wherever:
...
JAXBContext jc = JAXBContext.newInstance(Wrapper.class, clazz);
...
public String marshal(List<T> things, Class clazz) {
//configure JAXB and marshaller
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//Create wrapper based on generic list of objects
Wrapper<T> wrapper = new Wrapper<T>(things);
JAXBElement<Wrapper> wrapperJAXBElement = new JAXBElement<Wrapper>(new QName(clazz.getSimpleName().toLowerCase()+"s"), Wrapper.class, wrapper);
StringWriter result = new StringWriter();
//marshal!
m.marshal(wrapperJAXBElement, result);
return result.toString();
}
The latest release of Requests will build CookieJars for you from simple dictionaries.
import requests
cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
r = requests.post('http://wikipedia.org', cookies=cookies)
Enjoy :)
You can use this js code. Just change .post-thumb img
with your img
.
$('.post-thumb img').each(function(){ // Note: {.post-thumb img} is css selector of the image tag
var t = $(this),
s = 'url(' + t.attr('src') + ')',
p = t.parent(),
d = $('<div></div>');
t.hide();
p.append(d);
d.css({
'height' : 260, // Note: You can change it for your needs
'background-size' : 'cover',
'background-repeat' : 'no-repeat',
'background-position' : 'center',
'background-image' : s
});
});
Keep your scripts right before </body>
. Async can be used with scripts located there in a few circumstances (see discussion below). Defer won't make much of a difference for scripts located there because the DOM parsing work has pretty much already been done anyway.
Here's an article that explains the difference between async and defer: http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/.
Your HTML will display quicker in older browsers if you keep the scripts at the end of the body right before </body>
. So, to preserve the load speed in older browsers, you don't want to put them anywhere else.
If your second script depends upon the first script (e.g. your second script uses the jQuery loaded in the first script), then you can't make them async without additional code to control execution order, but you can make them defer because defer scripts will still be executed in order, just not until after the document has been parsed. If you have that code and you don't need the scripts to run right away, you can make them async or defer.
You could put the scripts in the <head>
tag and set them to defer
and the loading of the scripts will be deferred until the DOM has been parsed and that will get fast page display in new browsers that support defer, but it won't help you at all in older browsers and it isn't really any faster than just putting the scripts right before </body>
which works in all browsers. So, you can see why it's just best to put them right before </body>
.
Async is more useful when you really don't care when the script loads and nothing else that is user dependent depends upon that script loading. The most often cited example for using async is an analytics script like Google Analytics that you don't want anything to wait for and it's not urgent to run soon and it stands alone so nothing else depends upon it.
Usually the jQuery library is not a good candidate for async because other scripts depend upon it and you want to install event handlers so your page can start responding to user events and you may need to run some jQuery-based initialization code to establish the initial state of the page. It can be used async, but other scripts will have to be coded to not execute until jQuery is loaded.
Hello just create a simple function that looks as shown below.. That returns all rows where the call parameter entered is valid or true.
public DataTable SearchRecords(string Col1, DataTable RecordDT_, int KeyWORD)
{
TempTable = RecordDT_;
DataView DV = new DataView(TempTable);
DV.RowFilter = string.Format(string.Format("Convert({0},'System.String')",Col1) + " LIKE '{0}'", KeyWORD);
return DV.ToTable();
}
and simply call it as shown below;
DataTable RowsFound=SearchRecords("IdColumn", OriginalTable,5);
where 5 is the ID. Thanks..
int array[ROW][COLUMN]={1};
This initialises only the first element to 1. Everything else gets a 0.
In the first instance, you're doing the same - initialising the first element to 0, and the rest defaults to 0.
The reason is straightforward: for an array, the compiler will initialise every value you don't specify with 0.
With a char
array you could use memset
to set every byte, but this will not generally work with an int
array (though it's fine for 0).
A general for
loop will do this quickly:
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COLUMN; j++)
array[i][j] = 1;
Or possibly quicker (depending on the compiler)
for (int i = 0; i < ROW*COLUMN; i++)
*((int*)a + i) = 1;
The code is correct so I'm guessing that you are using an older JDK. The javadoc for that method says it has been there since 1.6. At the command line type:
java -version
I'm guessing that you are not running 1.6
Kotlin version that combines two best solutions
fun getStatusBarHeight(): Int {
val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
return if (resourceId > 0) resources.getDimensionPixelSize(resourceId)
else Rect().apply { window.decorView.getWindowVisibleDisplayFrame(this) }.top
}
status_bar_height
value if presentstatus_bar_height
is not present, calculates the status bar height from Window decor Install redis on your system first -
brew install redis
then start the redis server -
redis-server
The content inside strings in Golang can be compared using ==
operator. If the results are not as expected there may be some hidden characters like \n
, \r
, spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings
package in golang.
For Instance, spaces can be removed using strings.TrimSpace
function. You can also define a custom function to remove any character you need. strings.TrimFunc
function can give you more power.
A query of type MyEntity
is going to return MyEntity
. You want a query for a Long
.
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();
Obviously you will want to build up your expression with whatever restrictions and groupings etc you skipped in the example.
Spaces will not be a problem for cast
, however characters like TAB
, CR
or LF
will appear as spaces, will not be trimmed by LTRIM
or RTRIM
, and will be a problem.
For example try the following:
declare @v1 varchar(21) = '66',
@v2 varchar(21) = ' 66 ',
@v3 varchar(21) = '66' + char(13) + char(10),
@v4 varchar(21) = char(9) + '66'
select cast(@v1 as int) -- ok
select cast(@v2 as int) -- ok
select cast(@v3 as int) -- error
select cast(@v4 as int) -- error
Check your input for these characters and if you find them, use REPLACE
to clean up your data.
Per your comment, you can use REPLACE
as part of your cast
:
select cast(replace(replace(@v3, char(13), ''), char(10), '') as int)
If this is something that will be happening often, it would be better to clean up the data and modify the way the table is populated to remove the CR
and LF
before it is entered.
i was getting an error saying Permission Denied after running any 'ng' command (ng --version). I googled for a while and tried clearing npm cache npm cache verify
, uninstalling my global angular cli (npm uninstall -g @angular/cli
) and reinstalling Angular/cli (npm install -g @angular/cli
) etc.. but it would give an error say its already installed. but the node_modules folder here wouldn't have any angular folder.. reinstalled node even then restarted my computer.
ANSWER: Finally I found that the ng.cmd and ng.ps1 files in C:\Users\JaGoodwin\AppData\Roaming\npm\
here were still there (in npm folder).. even though I did npm uninstall -g @angular/cli
. those files were causing ng (angular/cli) to think it was still installed. i deleted those files then npm install -g @angular/[email protected]
(version i need) I then removed my projects node_modules and then ran npm install
and now can run my angular project using ng serve
.
C:\Users\JaGoodwin\AppData\Roaming\npm\
Find this by folder searching %APPDATA% in your windows search bar.
l.index(x)
returns the smallest i such that i is the index of the first occurrence of x in the list.
One can safely assume that the index()
function in Python is implemented so that it stops after finding the first match, and this results in an optimal average performance.
For finding an element stopping after the first match in a NumPy array use an iterator (ndenumerate).
In [67]: l=range(100)
In [68]: l.index(2)
Out[68]: 2
NumPy array:
In [69]: a = np.arange(100)
In [70]: next((idx for idx, val in np.ndenumerate(a) if val==2))
Out[70]: (2L,)
Note that both methods index()
and next
return an error if the element is not found. With next
, one can use a second argument to return a special value in case the element is not found, e.g.
In [77]: next((idx for idx, val in np.ndenumerate(a) if val==400),None)
There are other functions in NumPy (argmax
, where
, and nonzero
) that can be used to find an element in an array, but they all have the drawback of going through the whole array looking for all occurrences, thus not being optimized for finding the first element. Note also that where
and nonzero
return arrays, so you need to select the first element to get the index.
In [71]: np.argmax(a==2)
Out[71]: 2
In [72]: np.where(a==2)
Out[72]: (array([2], dtype=int64),)
In [73]: np.nonzero(a==2)
Out[73]: (array([2], dtype=int64),)
Just checking that for large arrays the solution using an iterator is faster when the searched item is at the beginning of the array (using %timeit
in the IPython shell):
In [285]: a = np.arange(100000)
In [286]: %timeit next((idx for idx, val in np.ndenumerate(a) if val==0))
100000 loops, best of 3: 17.6 µs per loop
In [287]: %timeit np.argmax(a==0)
1000 loops, best of 3: 254 µs per loop
In [288]: %timeit np.where(a==0)[0][0]
1000 loops, best of 3: 314 µs per loop
This is an open NumPy GitHub issue.
See also: Numpy: find first index of value fast
Here a more flexible variant based on @Mark Baker post:
foreach (range('A', $phpExcelObject->getActiveSheet()->getHighestDataColumn()) as $col) {
$phpExcelObject->getActiveSheet()
->getColumnDimension($col)
->setAutoSize(true);
}
Hope this helps ;)
The simplest way I found is:
$date = new DateTime(); //this returns the current date time
$result = $date->format('Y-m-d-H-i-s');
echo $result . "<br>";
$krr = explode('-', $result);
$result = implode("", $krr);
echo $result;
I hope it helps.
If you, like me, would rather use some library code where they probably have thought of all special cases, such as what happens if you pass in null or dots in the path but not in the filename, you can use the following:
import org.apache.commons.io.FilenameUtils;
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);
select region,sum(number) total
from
(
select region,number
from cash_table
union all
select region,number
from cheque_table
) t
group by region
You can create an array with a range using splat,
>> a=*(1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
using Kernel
Array
method,
Array (1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
or using to_a
(1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
docker ps -s will show the size of running containers only.
To check the size of all containers use docker ps -as
Unfortunately there is no SELECT statement that will always work regardless of database.
Most databases support:
SELECT 1
Some databases don't support this but have a table called DUAL that you can use when you don't need a table:
SELECT 1 FROM DUAL
MySQL also supports this for compatibility reasons, but not all databases do. A workaround for databases that don't support either of the above is to create a table called DUAL that contains a single row, then the above will work.
HSQLDB supports neither of the above, so you can either create the DUAL table or else use:
SELECT 1 FROM any_table_that_you_know_exists_in_your_database
The accepted answer helped me but I got tripped up while doing concatenation of varchars involving case statements. I know the OP's question does not involve case statements but I thought this would be helpful to post here for others like me who ended up here while struggling to build long dynamic SQL statements involving case statements.
When using case statements with string concatenation the rules mentioned in the accepted answer apply to each section of the case statement independently.
declare @l_sql varchar(max) = ''
set @l_sql = @l_sql +
case when 1=1 then
--without this correction the result is truncated
--CONVERT(VARCHAR(MAX), '')
+REPLICATE('1', 8000)
+REPLICATE('1', 8000)
end
print len(@l_sql)
you could also use display: table
insted of tables. Divs are way more flexible than tables.
Example:
.table {_x000D_
display: table;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.table .table-row {_x000D_
display: table-row;_x000D_
}_x000D_
_x000D_
.table .table-cell {_x000D_
display: table-cell;_x000D_
text-align: left;_x000D_
vertical-align: top;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="table-row">_x000D_
<div class="table-cell">test</div>_x000D_
<div class="table-cell">test1123</div>_x000D_
</div>_x000D_
<div class="table-row">_x000D_
<div class="table-cell">test</div>_x000D_
<div class="table-cell">test123</div>_x000D_
</div>_x000D_
</div>
_x000D_
One more good point here is to use @JsonFilter
.
Some details here http://wiki.fasterxml.com/JacksonFeatureJsonFilter
If you're in a heavily concurrent environment, then pure functional programming is useful. The lack of mutable state makes concurrency almost trivial. See Erlang.
In a multiparadigm language, you may want to model some things functionally if the existence of mutable state is must an implementation detail, and thus FP is a good model for the problem domain. For example, see list comprehensions in Python or std.range in the D programming language. These are inspired by functional programming.
SVG 1.2 Tiny has viewport-fill I'm not sure how widely implemented this property is though as most browsers are targetting SVG 1.1 at this time. Opera implements it FWIW.
A more cross-browser solution currently would be to stick a <rect>
element with width and height of 100% and fill="red" as the first child of the <svg>
element, for example:
<rect width="100%" height="100%" fill="red"/>
The JAXB APIs are considered to be Java EE APIs and therefore are no longer contained on the default classpath in Java SE 9. In Java 11, they are completely removed from the JDK.
Java 9 introduces the concepts of modules, and by default, the java.se
aggregate module is available on the classpath (or rather, module-path). As the name implies, the java.se
aggregate module does not include the Java EE APIs that have been traditionally bundled with Java 6/7/8.
Fortunately, these Java EE APIs that were provided in JDK 6/7/8 are still in the JDK, but they just aren't on the classpath by default. The extra Java EE APIs are provided in the following modules:
java.activation
java.corba
java.transaction
java.xml.bind << This one contains the JAXB APIs
java.xml.ws
java.xml.ws.annotation
Quick and dirty solution: (JDK 9/10 only)
To make the JAXB APIs available at runtime, specify the following command-line option:
--add-modules java.xml.bind
But I still need this to work with Java 8!!!
If you try specifying --add-modules
with an older JDK, it will blow up because it's an unrecognized option. I suggest one of two options:
JDK_JAVA_OPTIONS
environment variable. This environment variable is automatically read by the java
launcher for Java 9+.-XX:+IgnoreUnrecognizedVMOptions
to make the JVM silently ignore unrecognized options, instead of blowing up. But beware! Any other command-line arguments you use will no longer be validated for you by the JVM. This option works with Oracle/OpenJDK as well as IBM JDK (as of JDK 8sr4).Alternate quick solution: (JDK 9/10 only)
Note that you can make all of the above Java EE modules available at run time by specifying the --add-modules java.se.ee
option. The java.se.ee
module is an aggregate module that includes java.se.ee
as well as the above Java EE API modules. Note, this doesn't work on Java 11 because java.se.ee
was removed in Java 11.
The Java EE API modules listed above are all marked @Deprecated(forRemoval=true)
because they are scheduled for removal in Java 11. So the --add-module
approach will no longer work in Java 11 out-of-the-box.
What you will need to do in Java 11 and forward is include your own copy of the Java EE APIs on the classpath or module path. For example, you can add the JAX-B APIs as a Maven dependency like this:
<!-- API, java.xml.bind module -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.2</version>
</dependency>
<!-- Runtime, com.sun.xml.bind module -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.2</version>
</dependency>
See the JAXB Reference Implementation page for more details on JAXB.
For full details on Java modularity, see JEP 261: Module System
For Gradle or Android Studio developer: (JDK 9 and beyond)
Add the following dependencies to your build.gradle
file:
dependencies {
// JAX-B dependencies for JDK 9+
implementation "jakarta.xml.bind:jakarta.xml.bind-api:2.3.2"
implementation "org.glassfish.jaxb:jaxb-runtime:2.3.2"
}
It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.
In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.
It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.
According to this page https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/Attributes.html it is only available if (Enabled only in a UIWebView with the allowsInlineMediaPlayback property set to YES.) I understand in Mobile Safari this is YES on iPad and NO on iPhone and iPod Touch.
For example, like this:
const querystring = require('querystring');
const https = require('https');
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'posttestserver.com',
port: 443,
path: '/post.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(postData);
req.end();
We can use,
$ rails d migration table_name
Which will delete the migration.
No, it is not possible to change the content of the buttons in the dialog displayed by the confirm
function. You can use Javascript to create a dialog that looks similar.
if you are interested in a ready solution then you may look at HumanizerCpp library (https://github.com/trodevel/HumanizerCpp) - it is a port of C# Humanizer library and it does exactly what you want.
It can even convert to ordinals and currently supports 3 languages: English, German and Russian.
Example:
const INumberToWordsConverter * e = Configurator::GetNumberToWordsConverter( "en" );
std::cout << e->Convert( 123 ) << std::endl;
std::cout << e->Convert( 1234 ) << std::endl;
std::cout << e->Convert( 12345 ) << std::endl;
std::cout << e->Convert( 123456 ) << std::endl;
std::cout << std::endl;
std::cout << e->ConvertToOrdinal( 1001 ) << std::endl;
std::cout << e->ConvertToOrdinal( 1021 ) << std::endl;
const INumberToWordsConverter * g = Configurator::GetNumberToWordsConverter( "de" );
std::cout << std::endl;
std::cout << g->Convert( 123456 ) << std::endl;
const INumberToWordsConverter * r = Configurator::GetNumberToWordsConverter( "ru" );
std::cout << r->ConvertToOrdinal( 1112 ) << std::endl;
Output:
one hundred and twenty-three
one thousand two hundred and thirty-four
twelve thousand three hundred and forty-five
one hundred and twenty-three thousand four hundred and fifty-six
thousand and first
thousand and twenty-first
einhundertdreiundzwanzigtausendvierhundertsechsundfünfzig
???? ?????? ??? ???????????
In any case you may take a look at the source code and reuse in your project or try to understand the logic. It is written in pure C++ without external libraries.
Regards, Serge
Linux users can find the locations of all the installed packages like this:
pip list | xargs -exec pip show
Sometimes it's better to think like a parser, like T-SQL parser. While executing the statement, parser does not have any value in Pivot section and you can't have any check expression in that section. By the way, you can simply use this:
SELECT CLASS
, IsNull([AZ], 0)
, IsNull([CA], 0)
, IsNull([TX], 0)
FROM #TEMP
PIVOT (
SUM(DATA)
FOR STATE IN (
[AZ]
, [CA]
, [TX]
)
) AS PVT
ORDER BY CLASS
|*| Sorting an List :
import java.util.Collections;
|=> Sort Asc Order :
Collections.sort(NamAryVar);
|=> Sort Dsc Order :
Collections.sort(NamAryVar, Collections.reverseOrder());
|*| Reverse the order of List :
Collections.reverse(NamAryVar);
Using the simple app.run()
from within Flask creates a single synchronous server on a single thread capable of serving only one client at a time. It is intended for use in controlled environments with low demand (i.e. development, debugging) for exactly this reason.
Spawning threads and managing them yourself is probably not going to get you very far either, because of the Python GIL.
That said, you do still have some good options. Gunicorn is a solid, easy-to-use WSGI server that will let you spawn multiple workers (separate processes, so no GIL worries), and even comes with asynchronous workers that will speed up your app (and make it more secure) with little to no work on your part (especially with Flask).
Still, even Gunicorn should probably not be directly publicly exposed. In production, it should be used behind a more robust HTTP server; nginx tends to go well with Gunicorn and Flask.
Maven is not designed to work that way, but a workaround exists to achieve this goal (maybe with side effects, you will have to give a try). The trick is to tell the child project to find its parent via its relative path rather than its pure maven coordinates, and in addition to externalize the version number in a property :
<groupId>com.dummy.bla</groupId>
<artifactId>parent</artifactId>
<version>${global.version}</version>
<packaging>pom</packaging>
<properties>
<!-- Unique entry point for version number management -->
<global.version>0.1-SNAPSHOT</global.version>
</properties>
<parent>
<groupId>com.dummy.bla</groupId>
<artifactId>parent</artifactId>
<version>${global.version}</version>
<relativePath>..</relativePath>
</parent>
<groupId>com.dummy.bla.sub</groupId>
<artifactId>kid</artifactId>
I used that trick for a while for one of my project, with no specific problem, except the fact that maven logs a lot of warnings at the beginning of the build, which is not very elegant.
Seems maven 3.0.4 does not allow such a configuration anymore.
If you're using less , and it's not loading the icons font you must check out the font path go to the file variable.less and change the @icon-font-path path , that worked for me.
Use value(cellref)
on the side to evaluate the cells. Strings will produce the "#Value" error, but dates resolve to a number (e.g. 43173
).
for listener support no services you can use the following command to set local_listener paramter in your spfile use your listener port and server ip address
alter system set local_listener='(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.1.101)(PORT=1520)))' sid='testdb' scope=spfile;
Just to shed some light on this.
After I deleted my p12 certificate from Keychain. I re-downloaded my own certificate from Apple developer portal.
I was only able to download the certificate. But to sign you need the private key as well. So you either:
export both private key and certificate from Keychain to get it.
Upload a Certificate Signing Request and generate new certificates
That certificate by itself has no value for signing purposes. My guess is that the private key is created by keychain the moment you 'request a certificate from a certificate authority' but isn't shown to you until you add its tying certificate.
Another to answer this question available here answered by @nilesh https://stackoverflow.com/a/19934852/2079692
public void setAttributeValue(WebElement elem, String value){
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])",
elem, "value", value
);
}
this takes advantage of selenium findElementBy function where xpath can be used also.
Numbers have higher precedence than strings so of course the +
operators want to convert your strings into numbers before adding.
You could do:
print 'There are ' + CONVERT(varchar(10),@Number) +
' alias combinations did not match a record'
or use the (rather limited) formatting facilities of RAISERROR
:
RAISERROR('There are %i alias combinations did not match a record',10,1,@Number)
WITH NOWAIT
Someone edited my answer to add incorrect English, but here was the original, which is inferior to the accepted answer.
. .bashrc
A reference is semantically the following:
T& <=> *(T * const)
const T& <=> *(T const * const)
T&& <=> [no C equivalent]
(C++11)
As with other answers, the following from the C++ FAQ is the one-line answer: references when possible, pointers when needed.
An advantage over pointers is that you need explicit casting in order to pass NULL. It's still possible, though. Of the compilers I've tested, none emit a warning for the following:
int* p() {
return 0;
}
void x(int& y) {
y = 1;
}
int main() {
x(*p());
}
A bit of a late entry - but hopefully still useful to someone out there:-
Here's a simplified snippet for sending an in-memory string as an email attachment (a CSV file in this particular case).
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream)) // using UTF-8 encoding by default
using (var mailClient = new SmtpClient("localhost", 25))
using (var message = new MailMessage("[email protected]", "[email protected]", "Just testing", "See attachment..."))
{
writer.WriteLine("Comma,Seperated,Values,...");
writer.Flush();
stream.Position = 0; // read from the start of what was written
message.Attachments.Add(new Attachment(stream, "filename.csv", "text/csv"));
mailClient.Send(message);
}
The StreamWriter and underlying stream should not be disposed until after the message has been sent (to avoid ObjectDisposedException: Cannot access a closed Stream
).
Using org.apache.commons.io.FileUtils:
FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());
try this:
SELECT * FROM TableA
JOIN TableB ON TableA.primary_key = TableB.foreign_key
JOIN TableB ON TableB.foreign_key = TableC.foreign_key
All non-private instance methods are virtual by default in Java.
In C++, private methods can be virtual. This can be exploited for the non-virtual-interface (NVI) idiom. In Java, you'd need to make the NVI overridable methods protected.
From the Java Language Specification, v3:
8.4.8.1 Overriding (by Instance Methods) An instance method m1 declared in a class C overrides another instance method, m2, declared in class A iff all of the following are true:
- C is a subclass of A.
- The signature of m1 is a subsignature (§8.4.2) of the signature of m2.
- Either * m2 is public, protected or declared with default access in the same package as C, or * m1 overrides a method m3, m3 distinct from m1, m3 distinct from m2, such that m3 overrides m2.
Just to agree with everyone else: don't parse HTML using regexp.
It isn't possible to create an expression that will pick out attributes for even a correct piece of HTML, never mind all the possible malformed variants. Your regexp is already pretty much unreadable even without trying to cope with the invalid lack of quotes; chase further into the horror of real-world HTML and you will drive yourself crazy with an unmaintainable blob of unreliable expressions.
There are existing libraries to either read broken HTML, or correct it into valid XHTML which you can then easily devour with an XML parser. Use them.
Another late answer, but this is missing here. If you want to handle conversion of serialized /Date(1425408717000)/
in javascript, you can simply call:
var cSharpDate = "/Date(1425408717000)/"
var jsDate = new Date(parseInt(cSharpDate.replace(/[^0-9 +]/g, '')));
Source: amirsahib
This short and clean code:
::-webkit-input-placeholder {color: red;}
:-moz-placeholder {color: red; /* For Firefox 18- */}
::-moz-placeholder {color: red; /* For Firefox 19+ */}
:-ms-input-placeholder {color: red;}
The onclick handler should return false after the function call. For eg.
onclick="ConfirmDelete(); return false;">
Maybe this repo will help for you:BasePopup
This is my repo, which is used to solve various problems of PopupWindow.
In the case of using the library, if you need to blur the background, just call setBlurBackgroundEnable(true).
See the wiki for more details.(Language in zh-cn)
Wrapper classes for primitives can be used where objects are required, collections are a good sample.
Imagine you need for some reason store a sequence of boolean
in an ArrayList
, this can be done by boxing boolean
in Boolean
.
There is a few words about this here
From documentation:
As any Java programmer knows, you can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.
http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html
$zip = new ZipArchive;
$tmp_file = 'assets/myzip.zip';
if ($zip->open($tmp_file, ZipArchive::CREATE)) {
$zip->addFile('folder/bootstrap.js', 'bootstrap.js');
$zip->addFile('folder/bootstrap.min.js', 'bootstrap.min.js');
$zip->close();
echo 'Archive created!';
header('Content-disposition: attachment; filename=files.zip');
header('Content-type: application/zip');
readfile($tmp_file);
} else {
echo 'Failed!';
}
I stumbled upon this thread and want to post another option. I'm using Luad generated from a block controller, but it essentially works by checking values in the table, then incrementing which value is being checked by 1. Eventually, the table will run out, and the value at that index will be Nil.
So subtract 1 from the index that returned a nil, and that's the size of the table.
I have a global Variable for TableSize that is set to the result of this count.
function Check_Table_Size()
local Count = 1
local CurrentVal = (CueNames[tonumber(Count)])
local repeating = true
print(Count)
while repeating == true do
if CurrentVal ~= nil then
Count = Count + 1
CurrentVal = CueNames[tonumber(Count)]
else
repeating = false
TableSize = Count - 1
end
end
print(TableSize)
end
To setup GruntJS build here is the steps:
Make sure you have setup your package.json
or setup new one:
npm init
Install Grunt CLI as global:
npm install -g grunt-cli
Install Grunt in your local project:
npm install grunt --save-dev
Install any Grunt Module you may need in your build process. Just for sake of this sample I will add Concat module for combining files together:
npm install grunt-contrib-concat --save-dev
Now you need to setup your Gruntfile.js
which will describe your build process. For this sample I just combine two JS files file1.js
and file2.js
in the js
folder and generate app.js
:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
concat: {
"options": { "separator": ";" },
"build": {
"src": ["js/file1.js", "js/file2.js"],
"dest": "js/app.js"
}
}
});
// Load required modules
grunt.loadNpmTasks('grunt-contrib-concat');
// Task definitions
grunt.registerTask('default', ['concat']);
};
Now you'll be ready to run your build process by following command:
grunt
I hope this give you an idea how to work with GruntJS build.
NOTE:
You can use grunt-init
for creating Gruntfile.js
if you want wizard-based creation instead of raw coding for step 5.
To do so, please follow these steps:
npm install -g grunt-init
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
grunt-init gruntfile
For Windows users: If you are using cmd.exe you need to change ~/.grunt-init/gruntfile
to %USERPROFILE%\.grunt-init\
. PowerShell will recognize the ~
correctly.
I solved my slow Git problem on Windows 7 x64 by starting cmd.exe with "Run as administrator".
if you want selector get the same id, use:
$("[id=task]:eq(0)").val();
$("[id=task]:eq(1)").val();
etc...
I think you should use SO_LINGER options (with timeout 0). In this case, you connection will close immediately after closing your program; and next restart will be able to bind again.
example:
linger lin;
lin.l_onoff = 0;
lin.l_linger = 0;
setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char *)&lin, sizeof(int));
see definition: http://man7.org/linux/man-pages/man7/socket.7.html
SO_LINGER
Sets or gets the SO_LINGER option. The argument is a linger
structure.
struct linger {
int l_onoff; /* linger active */
int l_linger; /* how many seconds to linger for */
};
When enabled, a close(2) or shutdown(2) will not return until
all queued messages for the socket have been successfully sent
or the linger timeout has been reached. Otherwise, the call
returns immediately and the closing is done in the background.
When the socket is closed as part of exit(2), it always
lingers in the background.
More about SO_LINGER: TCP option SO_LINGER (zero) - when it's required
Forward is a great tool for helping with development of facebook apps locally, it supports SSL so the cert thing isn't a problem.
https://forwardhq.com/in-use/facebook
DISCLAIMER: I'm one of the devs
I just set the timezone with Matthias Bauch answer And it worked for me. else it was adding 18:30 min more.
let cal: NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let newDate: NSDate = cal.dateBySettingHour(1, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!
db.users.count()
db.users.remove({})
db.users.count()
I would say the most elegant way is this:
<div class="toggle"></div>
<div class="content">...</div>
then css:
.toggle{
display:inline-block;
height:48px;
width:48px; background:url("http://icons.iconarchive.com/icons/pixelmixer/basic/48/plus-icon.png");
}
.toggle.expanded{
background:url("http://cdn2.iconfinder.com/data/icons/onebit/PNG/onebit_32.png");
}
and js:
$(document).ready(function(){
var $content = $(".content").hide();
$(".toggle").on("click", function(e){
$(this).toggleClass("expanded");
$content.slideToggle();
});
});
Credit to @Gert Grenander , @Alaa.Kh , and Ross Shanon
Trying to make some order:
it all works - all but the firefox bookmarking function. for some reason the 'window.sidebar.addPanel' is not a function for the debugger, though it is working fine.
The problem is that it takes its values from the calling <a ..>
tag: title as the bookmark name and href as the bookmark address.
so this is my code:
javascript:
$("#bookmarkme").click(function () {
var url = 'http://' + location.host; // i'm in a sub-page and bookmarking the home page
var name = "Snir's Homepage";
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1){ //chrome
alert("In order to bookmark go to the homepage and press "
+ (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ?
'Command/Cmd' : 'CTRL') + "+D.")
}
else if (window.sidebar) { // Mozilla Firefox Bookmark
//important for firefox to add bookmarks - remember to check out the checkbox on the popup
$(this).attr('rel', 'sidebar');
//set the appropriate attributes
$(this).attr('href', url);
$(this).attr('title', name);
//add bookmark:
// window.sidebar.addPanel(name, url, '');
// window.sidebar.addPanel(url, name, '');
window.sidebar.addPanel('', '', '');
}
else if (window.external) { // IE Favorite
window.external.addFavorite(url, name);
}
return;
});
html:
<a id="bookmarkme" href="#" title="bookmark this page">Bookmark This Page</a>
In internet explorer there is a different between 'addFavorite':
<a href="javascript:window.external.addFavorite('http://tiny.cc/snir','snir-site')">..</a>
and 'AddFavorite': <span onclick="window.external.AddFavorite(location.href, document.title);">..</span>
.
example here: http://www.yourhtmlsource.com/javascript/addtofavorites.html
Important, in chrome we can't add bookmarks using js (aspnet-i): http://www.codeproject.com/Questions/452899/How-to-add-bookmark-in-Google-Chrome-Opera-and-Saf
I found this will have git ignore temporary files created by vim:
[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
*.un~
Session.vim
.netrwhist
*~
It can also be viewed here.
Add Jackson databind:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0.pr2</version>
</dependency>
Create DTO class with related fields and read JSON file:
ObjectMapper objectMapper = new ObjectMapper();
ExampleClass example = objectMapper.readValue(new File("example.json"), ExampleClass.class);
I'd go with H2, the performance is meant to much better than Derby. Read http://www.h2database.com/html/performance.html for more info.
You can change using the .bat make sure you run the call command prior, hopefully this helps anyone in future making similar .bat commands
call npm config set registry https://registry.npmjs.org/
For testing purposes I use the following:
//return assoc array when called from outside the class it will only contain public properties and values
var_dump(get_object_vars($obj));
printStackTrace() helps the programmer to understand where the actual problem occurred. It helps to trace the exception. it is printStackTrace() method of Throwable class inherited by every exception class. This method prints the same message of e object and also the line number where the exception occurred.
The following is an another example of print stack of the Exception in Java.
public class Demo {
public static void main(String[] args) {
try {
ExceptionFunc();
} catch(Throwable e) {
e.printStackTrace();
}
}
public static void ExceptionFunc() throws Throwable {
Throwable t = new Throwable("This is new Exception in Java...");
StackTraceElement[] trace = new StackTraceElement[] {
new StackTraceElement("ClassName","methodName","fileName",5)
};
t.setStackTrace(trace);
throw t;
}
}
java.lang.Throwable: This is new Exception in Java... at ClassName.methodName(fileName:5)
You have declared your function as friend
. It's not a member of the class. You should remove Matrix::
from the implementation. friend
means that the specified function (which is not a member of the class) can access private member variables. The way you implemented the function is like an instance method for Matrix
class which is wrong.
1st option -
You can nest REPLACE()
functions up to 32 levels deep. It runs fast.
REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE (@str, '0', ''),
'1', ''),
'2', ''),
'3', ''),
'4', ''),
'5', ''),
'6', ''),
'7', ''),
'8', ''),
'9', '')
2nd option -- do the reverse of -
Removing nonnumerical data out of a number + SQL
3rd option - if you want to use regex
(ugly) Double Brace Initialization without side effects:
Set<String> a = new HashSet<>(new HashSet<String>() {{
add("1");
add("2");
}})
But in some cases, if we mentioned that is a good smell to make final collections unmutable, it could be really useful:
final Set<String> a = Collections.unmodifiableSet(new HashSet<String>(){{
add("1");
add("2");
}})
you can use concat([df1, df2, ...], axis=1) in order to concatenate two or more DFs aligned by indexes:
pd.concat([df1, df2, df3, ...], axis=1)
or merge for concatenating by custom fields / indexes:
# join by _common_ columns: `col1`, `col3`
pd.merge(df1, df2, on=['col1','col3'])
# join by: `df1.col1 == df2.index`
pd.merge(df1, df2, left_on='col1' right_index=True)
or join for joining by index:
df1.join(df2)
Problem solved, I've not added the index.html. Which is point out in the web.xml
Note: a project may have more than one web.xml file.
if there are another web.xml in
src/main/webapp/WEB-INF
Then you might need to add another index (this time index.jsp) to
src/main/webapp/WEB-INF/pages/
Generate an array of random floats or ints of the same length. Sort that array, and do corresponding swaps on your target array.
This yields a truly independent sort.
Just for your information,after add the "PATH",for my win7 i need to reboot it to get it work.
You need to identify the columns based on their position in dataframe. For example, if you want to drop (del) column number 2,3 and 5, it will be,
df.drop(df.columns[[2,3,5]], axis = 1)
Cross Join: http://www.dba-oracle.com/t_garmany_9_sql_cross_join.htm
TLDR; Generates a all possible combinations between 2 tables (Carthesian product)
(Full) Outer Join: http://www.w3schools.com/Sql/sql_join_full.asp
TLDR; Returns every row in both tables and also results that have the same values (matches in CONDITION)
try this :
SET @StartDate = DATE_SUB(DATE(NOW()),INTERVAL (DAY(NOW())-1) DAY);
SET @EndDate = ADDDATE(CURDATE(),1);
select * from table where (date >= @StartDate and date < @EndDate);
Open the command line terminal where node application is running and press Ctrl + C
if you want to exit a node js application from code,
process.exit(); // graceful termination
process.exit(1); // non graceful termination
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
This should be the Unix load average. Wikipedia has a nice article about this.
The numbers show the average load of the CPU in different time intervals. From left to right: last minute/last five minutes/last fifteen minutes
It is possible to view a html file from terminal using lynx or links. But none of those browswers support the onload javascript feature. By using lynx or links you will have to actively click the submit button.
Move the Directory clause out of the virtualhost, and put it before declaring the virtualhost.
Drove me nuts for a long time too. Don't know why. It's a Debian thing.
This guide says:
6.1.5 Sending JDBC NULL as an IN parameter
The setNull method allows a programmer to send a JDBC NULL (a generic SQL NULL) value to the database as an IN parameter. Note, however, that one must still specify the JDBC type of the parameter.
A JDBC NULL will also be sent to the database when a Java null value is passed to a setXXX method (if it takes Java objects as arguments). The method setObject, however, can take a null value only if the JDBC type is specified.
So yes they're equivalent.
If you want to ignore the insertion of existing value, there must be a Key field in your Table. Just create a table With Primary Key Field Like:
CREATE TABLE IF NOT EXISTS TblUsers (UserId INTEGER PRIMARY KEY, UserName varchar(100), ContactName varchar(100),Password varchar(100));
And Then Insert Or Replace / Insert Or Ignore Query on the Table Like:
INSERT OR REPLACE INTO TblUsers (UserId, UserName, ContactName ,Password) VALUES('1','UserName','ContactName','Password');
It Will Not Let it Re-Enter The Existing Primary key Value... This Is how you can Check Whether a Value exists in the table or not.
The Python manual has this to say about id()
:
Return the "identity'' of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this is the address of the object.)
So in CPython, this will be the address of the object. No such guarantee for any other Python interpreter, though.
Note that if you're writing a C extension, you have full access to the internals of the Python interpreter, including access to the addresses of objects directly.
After you get from Eclipse the ugly CheckoutConflictException, the Eclipse-Merge Tool button is disabled.
Git need alle your files added to the Index for enable Merging.
So, to merge your Changes and commit them you need to add your files first to the index "Add to Index" and "Commit" them without "Push". Then you should see one pending pull and one pending push request in Eclipse. You see that in one up arrow and one down arrow.
If all conflict Files are in the commit, you can "pull" again. Then you will see something like:
\< < < < < < < HEAD Server Version \======= Local Version > > > > > > > branch 'master' of ....git
Then you either change it by the Merge-Tool, which is now enable or just do the merge by hand direct in the file. In the last step, you have to add the modified files again to the index and "Commit and Push" them.
Checking done!
Here what I understood from the question is starting with "a " and then "b" ex:
So there should be two conditions and both should be true means you cant use "OR" operator Ordered by is not not compulsory but its good if you use.
Select e_name from emp
where e_name like 'a%' AND e_name like '_b%'
Ordered by e_name
add following
setenv JAVA_HOME /System/Library/Frameworks/JavaVM.framework/Home
in your ~/.login file:
I solved this like this:
<section className="container-fluid">
<div className="row justify-content-center">
<article className="d-flex flex-column justify-content-center align-items-center vh-100">
<!-- content -->
</article>
</div>
</section>
Leveraging the power of java.util.Optional#map()
:
List<Car> requiredCars = cars.stream()
.filter (car ->
Optional.ofNullable(car)
.map(Car::getName)
.map(name -> name.startsWith("M"))
.orElse(false) // what to do if either car or getName() yields null? false will filter out the element
)
.collect(Collectors.toList())
;
By default mongodb has no enabled access control, so there is no default user or password.
To enable access control, use either the command line option --auth
or security.authorization configuration file setting.
You can use the following procedure or refer to Enabling Auth in the MongoDB docs.
Start MongoDB without access control.
mongod --port 27017 --dbpath /data/db1
Connect to the instance.
mongo --port 27017
Create the user administrator.
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Re-start the MongoDB instance with access control.
mongod --auth --port 27017 --dbpath /data/db1
Authenticate as the user administrator.
mongo --port 27017 -u "myUserAdmin" -p "abc123" \
--authenticationDatabase "admin"
Try this for getting form input text value to JavaScript object...
var fieldPair = {};
$("#form :input").each(function() {
if($(this).attr("name").length > 0) {
fieldPair[$(this).attr("name")] = $(this).val();
}
});
console.log(fieldPair);
Thorbjørn Ravn Andersen answered for most of the data types. Since there was a heated discussion about array,
Quoting from the jls spec http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5 "array component is initialized with a default value when it is created"
I think irrespective of whether array is local or instance or class variable it will with default values
The cex
parameter will do that for you.
a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
col = 1:6, space = c(0, 2))
legend("topright",
legend = c("a", "b", "c", "d", "e", "f"),
fill = 1:6, ncol = 2,
cex = 0.75)
Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then
method will be resolved differently depending on what the handler fn returns:
if the handler function:
- returns a value, the promise returned by then gets resolved with the returned value as its value;
- throws an error, the promise returned by then gets rejected with the thrown error as its value;
- returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
- returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
- returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.
You said :
Maybe my data.frame is not in a good format?
Yes this is true. Your data is in the wide format You need to put it in the long format. Generally speaking, long format is better for variables comparison.
Using reshape2
for example , you do this using melt
:
dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work
Then you get your barplot:
ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) +
geom_bar(stat='identity')
But using lattice
and barchart
smart formula notation , you don't need to reshape your data , just do this:
barchart(F1+F2+F3~Rank,data=dat)
If you develop in multiple IDE's or other programs that connect to AVD you should try closing them too.
Netbeans also can cause conflicts with eclipse if you set it up for NBAndroid.
here's how:
import pygame
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=90
height=90
filled=0
pygame.draw.rect(screen, [red, blue, green], [left, top, width, height], filled)
pygame.display.flip()
running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
pygame.quit()
This is a ready to use code, merging four pdf files with itext.jar from http://central.maven.org/maven2/com/itextpdf/itextpdf/5.5.0/itextpdf-5.5.0.jar, more on http://tutorialspointexamples.com/
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
/**
* This class is used to merge two or more
* existing pdf file using iText jar.
*/
public class PDFMerger {
static void mergePdfFiles(List<InputStream> inputPdfList,
OutputStream outputStream) throws Exception{
//Create document and pdfReader objects.
Document document = new Document();
List<PdfReader> readers =
new ArrayList<PdfReader>();
int totalPages = 0;
//Create pdf Iterator object using inputPdfList.
Iterator<InputStream> pdfIterator =
inputPdfList.iterator();
// Create reader list for the input pdf files.
while (pdfIterator.hasNext()) {
InputStream pdf = pdfIterator.next();
PdfReader pdfReader = new PdfReader(pdf);
readers.add(pdfReader);
totalPages = totalPages + pdfReader.getNumberOfPages();
}
// Create writer for the outputStream
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
//Open document.
document.open();
//Contain the pdf data.
PdfContentByte pageContentByte = writer.getDirectContent();
PdfImportedPage pdfImportedPage;
int currentPdfReaderPage = 1;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
// Iterate and process the reader list.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
//Create page and add content.
while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
document.newPage();
pdfImportedPage = writer.getImportedPage(
pdfReader,currentPdfReaderPage);
pageContentByte.addTemplate(pdfImportedPage, 0, 0);
currentPdfReaderPage++;
}
currentPdfReaderPage = 1;
}
//Close document and outputStream.
outputStream.flush();
document.close();
outputStream.close();
System.out.println("Pdf files merged successfully.");
}
public static void main(String args[]){
try {
//Prepare input pdf file list as list of input stream.
List<InputStream> inputPdfList = new ArrayList<InputStream>();
inputPdfList.add(new FileInputStream("..\\pdf\\pdf_1.pdf"));
inputPdfList.add(new FileInputStream("..\\pdf\\pdf_2.pdf"));
inputPdfList.add(new FileInputStream("..\\pdf\\pdf_3.pdf"));
inputPdfList.add(new FileInputStream("..\\pdf\\pdf_4.pdf"));
//Prepare output stream for merged pdf file.
OutputStream outputStream =
new FileOutputStream("..\\pdf\\MergeFile_1234.pdf");
//call method to merge pdf files.
mergePdfFiles(inputPdfList, outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I've just spent a happy 30 minutes with this. I'd renamed the entities object, renamed the entry in the config file, but there's more ... you have to change the reference to the csdl as well
very easy to miss - if you're renaming, make sure you get everything ....
Make sure your code is in DOM Ready as pointed by rocket-hazmat
$('#RootNode').click(function(){
//do something
});
document.getElementById("RootNode").onclick = function(){//do something}
$(document).on("click", "#RootNode", function(){
//do something
});
Wrap Code in Dom Ready
$(document).ready(function(){
$('#RootNode').click(function(){
//do something
});
});
Paxdiablo's answer is absolutely correct.
To avoid writing the return value 1
twice, I would use this instead:
=IF(OR(ISBLANK(A1),TRIM(A1)=""),1,0)
There's an ongoing effort for a PDCurses port:
There is an actual Data Type called KeyValuePair, use like this
KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>("defaultkey", "defaultvalue");
For Laravel developers, directory issues can be a little bit pain. In my application, I was creating directories on the fly and moving files to this directory in my local environment successfully. Then on server, I was getting errors while moving files to newly created directory.
Here are the things that I have done and got a successful result at the end.
sudo find /path/to/your/laravel/root/directory -type f -exec chmod 664 {} \;
sudo find /path/to/your/laravel/root/directory -type d -exec chmod 775 {} \;
chcon -Rt httpd_sys_content_rw_t /path/to/my/file/upload/directory/in/laravel/project/
mkdir($save_path, 0755, true);
After making those changes on production server, I successfully created new directories and move files to them.
Finally, if you use File facade in Laravel you can do something like this:
File::makeDirectory($save_path, 0755, true);
Not sure if Access supports it, but in most engines (including SQL Server
) this is called a correlated subquery and works fine:
SELECT TypesAndBread.Type, TypesAndBread.TBName,
(
SELECT Count(Sandwiches.[SandwichID]) As SandwichCount
FROM Sandwiches
WHERE (Type = 'Sandwich Type' AND Sandwiches.Type = TypesAndBread.TBName)
OR (Type = 'Bread' AND Sandwiches.Bread = TypesAndBread.TBName)
) As SandwichCount
FROM TypesAndBread
This can be made more efficient by indexing Type
and Bread
and distributing the subqueries over the UNION
:
SELECT [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type,
(
SELECT COUNT(*) As SandwichCount
FROM Sandwiches
WHERE Sandwiches.Type = [Sandwiches Types].[Sandwich Type]
)
FROM [Sandwiches Types]
UNION ALL
SELECT [Breads].[Bread] As TBName, "Bread" As Type,
(
SELECT COUNT(*) As SandwichCount
FROM Sandwiches
WHERE Sandwiches.Bread = [Breads].[Bread]
)
FROM [Breads]
C - an older programming language that is described as Hands-on. As the programmer you must tell the program to do everything. Also this language will let you do almost anything. It does not support object orriented code. Thus no classes.
C++ - an extention language per se of C. In C code ++ means increment 1. Thus C++ is better than C. It allows for highly controlled object orriented code. Once again a very hands on language that goes into MUCH detail.
C# - Full object orriented code resembling the style of C/C++ code. This is really closer to JAVA. C# is the latest version of the C style languages and is very good for developing web applications.