What are CN, OU, DC?
From RFC2253 (UTF-8 String Representation of Distinguished Names):
String X.500 AttributeType ------------------------------ CN commonName L localityName ST stateOrProvinceName O organizationName OU organizationalUnitName C countryName STREET streetAddress DC domainComponent UID userid
What does the string from that query mean?
The string ("CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com"
) is a path from an hierarchical structure (DIT = Directory Information Tree) and should be read from right (root) to left (leaf).
It is a DN (Distinguished Name) (a series of comma-separated key/value pairs used to identify entries uniquely in the directory hierarchy). The DN is actually the entry's fully qualified name.
Here you can see an example where I added some more possible entries.
The actual path is represented using green.
The following paths represent DNs (and their value depends on what you want to get after the query is run):
"DC=gp,DC=gl,DC=google,DC=com"
"OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com"
"OU=People,DC=gp,DC=gl,DC=google,DC=com"
"OU=Groups,DC=gp,DC=gl,DC=google,DC=com"
"CN=QA-Romania,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com"
"CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com"
"CN=Diana Anton,OU=People,DC=gp,DC=gl,DC=google,DC=com"
Here is a JS fiddle http://jsfiddle.net/ke9kW/1/
As the others say, set the header to fixed, and start it with display: none
then jQuery
$(window).scroll(function () {
if ( $(this).scrollTop() > 200 && !$('header').hasClass('open') ) {
$('header').addClass('open');
$('header').slideDown();
} else if ( $(this).scrollTop() <= 200 ) {
$('header').removeClass('open');
$('header').slideUp();
}
});
where 200 is the height in pixels you'd like it to move down at. The addition of the open class is to allow us to run an elseif instead of just else, so some of the code doesn't unnecessarily run on every scrollevent, save a lil bit of memory
As far as I know it's not possible... but you can try something like this:
.underline _x000D_
{_x000D_
color: blue;_x000D_
border-bottom: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
<span class="underline">hello world</span>_x000D_
</div>
_x000D_
Need to use top comment but also pay attention to nextLine(). To eliminate this error only call
sc.nextLine()
Once from inside your while loop
while (sc.hasNextLine()) {sc.nextLine()...}
You are using while to look ahead only 1 line. Then using sc.nextLine() to read 2 lines ahead of the single line you asked the while loop to look ahead.
Also change the multiple IF statements to IF, ELSE to avoid reading more than one line also.
From server side, if we send any response, it will be sent in the form of byte type, so it will appear in the client as b'Response from server'
In order get rid of b'....'
simply use below code:
Server file:
stri="Response from server"
c.send(stri.encode())
Client file:
print(s.recv(1024).decode())
then it will print Response from server
If you want both to reference the same variable, one of them should have int k;
, and the other should have extern int k;
For this situation, you typically put the definition (int k;
) in one .cpp
file, and put the declaration (extern int k;
) in a header, to be included wherever you need access to that variable.
If you want each k
to be a separate variable that just happen to have the same name, you can either mark them as static
, like: static int k;
(in all files, or at least all but one file). Alternatively, you can us an anonymous namespace:
namespace {
int k;
};
Again, in all but at most one of the files.
In C, the compiler generally isn't quite so picky about this. Specifically, C has a concept of a "tentative definition", so if you have something like int k;
twice (in either the same or separate source files) each will be treated as a tentative definition, and there won't be a conflict between them. This can be a bit confusing, however, because you still can't have two definitions that both include initializers--a definition with an initializer is always a full definition, not a tentative definition. In other words, int k = 1;
appearing twice would be an error, but int k;
in one place and int k = 1;
in another would not. In this case, the int k;
would be treated as a tentative definition and the int k = 1;
as a definition (and both refer to the same variable).
You can do something like this:
public myform()
{
InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
this.myTableAdapter.Fill(this.myDataSet.someTable);
comboBox1.SelectedItem = null;
comboBox1.SelectedText = "--select--";
}
In case this is of use to some newer dev's because its not specified above. Just to be very explicit:
You need two things if using onConfigurationChanged:
An onConfigurationChanged
method in your Activity Class
Specify in your manifest which configuration changes will be handled by your onConfigurationChanged
method
The manifest snippet in the above answers, while no doubt correct for the particular app that manifest belongs to, is NOT exactly what you need to add in your manifest to trigger the onConfigurationChanged method in your Activity Class. i.e. the below manifest entry may not be correct for your app.
<activity name= ".MainActivity" android:configChanges="orientation|screenSize"/>
In the above manifest entry, there are various Android actions for android:configChanges=""
which can trigger the onCreate in your Activity lifecycle.
This is very important - The ones NOT Specified in the manifest are the ones that trigger your onCreate and The ones specified in the manifest are the ones that trigger your onConfigurationChanged
method in your Activity Class.
So you need to identify which config changes you need to handle yourself. For the Android Encyclopedically Challenged like me, I used the quick hints pop-out in Android Studio and added in almost every possible configuration option. Listing all of these basically said that I would handle everything and onCreate will never be called due to configurations.
<activity name= ".MainActivity" android:configChanges="screenLayout|touchscreen|mnc|mcc|density|uiMode|fontScale|orientation|keyboard|layoutDirection|locale|navigation|smallestScreenSize|keyboardHidden|colorMode|screenSize"/>
Now obviously I don't want to handle everything, so I began eliminating the above options one at a time. Re-building and testing my app after each removal.
Another important point: If there is just one configuration option being handled automatically that triggers your onCreate (You do not have it listed in your manifest above), then it will appear like onConfigurationChanged
is not working. You must put all relevant ones into your manifest.
I ended up with 3 that were triggering onCreate originally, then I tested on an S10+ and I was still getting the onCreate, so I had to do my elimination exercise again and I also needed the |screenSize
. So test on a selection of platforms.
<activity name= ".MainActivity" android:configChanges="screenLayout|uiMode|orientation|screenSize"/>
So my suggestion, although I'm sure someone can poke holes in this:
Add your onConfigurationChanged
method in your Activity Class with a TOAST or LOG so you can see when its working.
Add all possible configuration options to your manifest.
Confirm your onConfigurationChanged
method is working by testing your app.
Remove each config option from your manifest file one at a time, testing your app after each.
Test on as large a variety of devices as possible.
Do not copy/paste my snippet above to your manifest file. Android updates change the list, so use the pop-out Android Studio hints to make sure you get them all.
I hope this saves someone some time.
My onConfigurationChanged
method just for info below. onConfigurationChanged
is called in the lifecycle after the new orientation is available, but before the UI has been recreated. Hence my first if
to check the orientation works correctly, and then the 2nd nested if
to look at the visibility of my UI ImageView also works correctly.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
pokerCardLarge = findViewById(R.id.pokerCardLgImageView);
if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
pokerCardLarge.setImageBitmap(image);
}
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
pokerCardLarge = findViewById(R.id.pokerCardLgImageView);
if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
pokerCardLarge.setImageBitmap(image);
}
}
}
See Popularity below textView using this
android:alpha="0.38"
XML
android:color="#3983BE00" // Partially transparent sky blue
Dynamically
btn.getBackground().setAlpha(128); // 50% transparent
tv_name.getBackground().setAlpha(128); // 50% transparent
Where the INT ranges from 0 (fully transparent) to 255 (fully opaque).
<TextView
style="@style/TextAppearance.AppCompat.Caption"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:alpha="0.38"
android:gravity="start"
android:textStyle="bold"
tools:text="1994|EN" />
android:alpha="0.38"
Text View alpha property set 0.38 to your textView visibility is faid
Little hack: you can prevent destroying your activity by GC (you should not do it, but it can help in some situations. Don't forget to set contextForDialog
to null
when it's no longer needed):
public class PostActivity extends Activity {
...
private Context contextForDialog = null;
...
public void onCreate(Bundle savedInstanceState) {
...
contextForDialog = this;
}
...
private void showAnimatedDialog() {
mSpinner = new Dialog(contextForDialog);
mSpinner.setContentView(new MySpinner(contextForDialog));
mSpinner.show();
}
...
}
Here on a openSuse 12.3 the solution was installing the 32-bit version of libaio in addition. Oracle seems to need this now, although on 12.1 it run without the 32-bit version.
I had let this go for a good while but revisited it later. Since this question is viewed regularly. This is eventually what I ended up using that worked for me.
define("DOC_ROOT","/path/to/html");
//username and password of account
$username = trim($values["email"]);
$password = trim($values["password"]);
//set the directory for the cookie using defined document root var
$path = DOC_ROOT."/ctemp";
//build a unique path with every request to store. the info per user with custom func. I used this function to build unique paths based on member ID, that was for my use case. It can be a regular dir.
//$path = build_unique_path($path); // this was for my use case
//login form action url
$url="https://www.example.com/login/action";
$postinfo = "email=".$username."&password=".$password;
$cookie_file_path = $path."/cookie.txt";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
//set the cookie the site has for certain features, this is optional
curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0");
curl_setopt($ch, CURLOPT_USERAGENT,
"Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
curl_exec($ch);
//page with the content I want to grab
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/page/");
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);
curl_close($ch);
Update: This code was never meant to be a copy and paste. It was to show how I used it for my specific use case. You should adapt it to your code as needed. Such as directories, vars etc
You can use HTML5 <figcaption>
:
<figure>
<img src="img.jpg" alt="my img"/>
<figcaption> Your text </figcaption>
</figure>
Apart from using the importlib
one can also use exec
method to import a module from a string variable.
Here I am showing an example of importing the combinations
method from itertools
package using the exec
method:
MODULES = [
['itertools','combinations'],
]
for ITEM in MODULES:
import_str = "from {0} import {1}".format(ITEM[0],', '.join(str(i) for i in ITEM[1:]))
exec(import_str)
ar = list(combinations([1, 2, 3, 4], 2))
for elements in ar:
print(elements)
Output:
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
http://dev.w3.org/webfonts/WOFF2/spec/#IMT
It seem that w3c switched it to font/woff2
I see there is some discussion about the proper mime type. In the link we read:
This document defines a top-level MIME type "font" ...
... the officially defined IANA subtypes such as "application/font-woff" ...
The members of the W3C WebFonts WG believe the use of "application" top-level type is not ideal.
and later
6.5. WOFF 2.0
Type name:
font
Subtype name:
woff2
So proposition from W3C differs from IANA.
We can see that it also differs from woff type: http://dev.w3.org/webfonts/WOFF/spec/#IMT where we read:
Type name:
application
Subtype name:
font-woff
which is
application/font-woff
Looks like you missed a few closing tags and you nshould have "http://" on the front of an external URL. Also, you should move your styles to external style sheets instead of using inline styles.
.box{
float:right;
}
.box a img{
vertical-align: middle;
border: 0px;
}
<div class="box">
<a href="<?php echo "http://www.someotherwebsite.com"; ?>">
<img src="<?php echo url::file_loc('img'); ?>media/img/twitter.png" alt="Image Decription">
</a>
</div>
As noted in other comments, it may be easier to use straight HTML, depending on your exact setup.
<div class="box">
<a href="http://www.someotherwebsite.com">
<img src="file_location/media/img/twitter.png" alt="Image Decription">
</a>
</div>
You could also be more restrictive in removing disallowed characters. The following regex would remove all characters that are not letters, digits or underscores:
$FileName = preg_replace('/[^\w]/', '', $UserInput);
You might want to do this to ensure maximum compatibility for filenames across different operating systems.
Use bulk_create()
method. It's standard in Django now.
Example:
Entry.objects.bulk_create([
Entry(headline="Django 1.0 Released"),
Entry(headline="Django 1.1 Announced"),
Entry(headline="Breaking: Django is awesome")
])
install PyQt5 for Windows 10 and python 3.5+.
pip install PyQt5
I have had the same problem, and the cause was that IIS was running ASP.NET 1.1, and the site required .NET 2.0.
The error message did nothing but throw me off track for several hours.
Dapper supports this directly. For example...
string sql = "SELECT * FROM SomeTable WHERE id IN @ids"
var results = conn.Query(sql, new { ids = new[] { 1, 2, 3, 4, 5 }});
You have 4 options:
$ pip install --cert /path/to/mycertificate.crt linkchecker
pip.conf
Create this file:
$HOME/.pip/pip.conf (Linux)
%HOME%\pip\pip.ini (Windows)
and add these lines:
[global]
cert = /path/to/mycertificate.crt
$ pip install --trusted-host pypi.python.org linkchecker
Create this file:
$HOME/.pip/pip.conf (Linux)
%HOME%\pip\pip.ini (Windows)
and add these lines:
[global]
trusted-host = pypi.python.org
The first constructor in the header should not end with a semicolon. #include <string>
is missing in the header. string
is not qualified with std::
in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream
is broken. I suggest learning C++ before trying to use it.
Let's fix this up:
//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__
#include <iostream>
#include <string>
class Polygone {
public:
// declarations have to end with a semicolon, definitions do not
Polygone(){} // why would we needs this?
Polygone(const std::string& fichier);
};
# endif
and
//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>
Polygone::Polygone(const std::string& nom)
{
std::ifstream fichier (nom, ios::in);
if (fichier.is_open())
{
// keep the scope as tiny as possible
std::string line;
// getline returns the stream and streams convert to booleans
while ( std::getline(fichier, line) )
{
std::cout << line << std::endl;
}
}
else
{
std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
}
}
Here the code to use your app.js
input specifies file name
res.download(__dirname+'/'+input);
if (character == character.toLowerCase())
{
// The character is lowercase
}
else
{
// The character is uppercase
}
I had this problem despite:
main()
; andMy eventual fix was the following:
main()
was in a namespace, so was effectively called something::main()
...removing this namespace fixed the problem.Try this:
var data = jQuery.parseJSON(response);
$.each(data, function(key, item)
{
console.log(item.com);
});
or
var data = $.parseJSON(response);
$(data).each(function(i,val)
{
$.each(val,function(key,val)
{
console.log(key + " : " + val);
});
});
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=
A word of caution here. In Objective-C, unlike many similar languages, you generally should try to avoid using exceptions for common error situations that may occur in normal operation.
Apple's documentation for Obj-C 2.0 states the following: "Important: Exceptions are resource-intensive in Objective-C. You should not use exceptions for general flow-control, or simply to signify errors (such as a file not being accessible)"
Apple's conceptual Exception handling documentation explains the same, but with more words: "Important: You should reserve the use of exceptions for programming or unexpected runtime errors such as out-of-bounds collection access, attempts to mutate immutable objects, sending an invalid message, and losing the connection to the window server. You usually take care of these sorts of errors with exceptions when an application is being created rather than at runtime. [.....] Instead of exceptions, error objects (NSError) and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors in Cocoa applications."
The reasons for this is partly to adhere to programming idioms in Objective-C (using return values in simple cases and by-reference parameters (often the NSError class) in more complex cases), partly that throwing and catching exceptions is much more expensive and finally (and perpaps most importantly) that Objective-C exceptions are a thin wrapper around C's setjmp() and longjmp() functions, essentially messing up your careful memory handling, see this explanation.
I was having this problem for Android-
URL- localhost/authToken.json - didn't work :(
URL- 10.106.105.103/authToken.json - didn't work :(
URL- http://10.106.105.103/authToken.json - worked :) :D
Note- Use ifconfig
on Linux or ipconfig
on Windows to find machine IpAddress
Why not just use all Lambda syntax?
database.Stores.Where(s => s.CompanyID == curCompany.ID)
.Select(s => new SelectListItem
{
Value = s.Name,
Text = s.ID
});
...
for(int i=0;i<3;i++){ //Rows
for(int j=0;j<5;j++){ //Cols
printf("%<...>\t",var);
}
printf("\n");
}
...
considering that <...> would be d,e,f,s,c... etc datatype... X)
As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.
This is some pseudocodish JavaScript:
Client:
var websocket = new WebSocket("server address");
websocket.onmessage = function(str) {
console.log("Someone sent: ", str);
};
// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
id: "client1"
}));
// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
to: "client2",
data: "foo"
}));
Server:
var clients = {};
server.on("data", function(client, str) {
var obj = JSON.parse(str);
if("id" in obj) {
// New client, add it to the id/client object
clients[obj.id] = client;
} else {
// Send data to the client requested
clients[obj.to].send(obj.data);
}
});
You can also rotate the ImageView
using a RotateAnimation
:
RotateAnimation rotateAnimation = new RotateAnimation(from, to,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotateAnimation.setInterpolator(new LinearInterpolator());
rotateAnimation.setDuration(ANIMATION_DURATION);
rotateAnimation.setFillAfter(true);
imageView.startAnimation(rotateAnimation);
Framework 4: no need to use StreamWriter:
System.IO.File.WriteAllLines("SavedLists.txt", Lists.verbList);
You can use the keyword IDENTITY
as the data type to the column along with PRIMARY KEY
constraint when creating the table.
ex:
StudentNumber IDENTITY(1,1) PRIMARY KEY
In here the first '1' means the starting value and the second '1' is the incrementing value.
Have both the buttons inside a div as shown below and add the given CSS for that div
#button1, #button2{_x000D_
width: 200px;_x000D_
height: 40px;_x000D_
}_x000D_
_x000D_
#butn{_x000D_
margin: 0 auto;_x000D_
display: block;_x000D_
}
_x000D_
<div id="butn">_x000D_
<button type="button home-button" id="button1" >Home</button>_x000D_
<button type="button contact-button" id="button2">Contact Us</button>_x000D_
<div>
_x000D_
CMD doesn't have time arithmetic. The following code, however gives a workaround:
set vid_time=11:07:48
set srt_time=11:16:58
REM Get time difference
set length=%vid_time%
for /f "tokens=1-3 delims=:" %i in ("%length%") do (
set /a h=%i*3600
set /a m=%j*60
set /a s=%k
)
set /a t1=!h!+!m!+!s!
set length=%srt_time%
for /f "tokens=1-3 delims=:" %i in ("%length%") do (
set /a h=%i*3600
set /a m=%j*60
set /a s=%k
)
set /a t2=!h!+!m!+!s!
cls
set /a diff=!t2!-!t1!
Above code gives difference in seconds. To display in hh:mm:ss format, code below:
set ss=!diff!
set /a hh=!ss!/3600 >nul
set /a mm="(!ss!-3600*!hh!)/60" >nul
set /a ss="(!ss!-3600*!hh!)-!mm!*60" >nul
set "hh=0!hh!" & set "mm=0!mm!" & set "ss=0!ss!"
echo|set /p=!hh:~-2!:!mm:~-2!:!ss:~-2!
Actually, to properly support sorting, filtering, etc. a CollectionViewSource should be used as a link between the DataGrid and the list, like this:
<Window.Resources>
<CollectionViewSource x:Key="ItemCollectionViewSource" CollectionViewType="ListCollectionView"/>
</Window.Resources>
The DataGrid line looks like this:
<DataGrid
DataContext="{StaticResource ItemCollectionViewSource}"
ItemsSource="{Binding}"
AutoGenerateColumns="False">
In the code behind, you link CollectionViewSource with your link.
CollectionViewSource itemCollectionViewSource;
itemCollectionViewSource = (CollectionViewSource)(FindResource("ItemCollectionViewSource"));
itemCollectionViewSource.Source = itemList;
For detailed example see my article on CoedProject: http://www.codeproject.com/Articles/683429/Guide-to-WPF-DataGrid-formatting-using-bindings
Try this:
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
<div class="form-group" ng-class="{'has-error': registration.phone.$error.number}">
<label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
<div class="col-sm-9">
<input type="number"
class="form-control"
ng-minlength="10"
ng-maxlength="10"
id="inputPhone"
name="phone"
placeholder="Phone"
ng-model="user.phone"
ng-required="true">
<span class="help-block"
ng-show="registration.phone.$error.required ||
registration.phone.$error.number">
Valid phone number is required
</span>
<span class="help-block"
ng-show="((registration.phone.$error.minlength ||
registration.phone.$error.maxlength) &&
registration.phone.$dirty) ">
phone number should be 10 digits
</span>
The json.dumps method can accept an optional parameter called default which is expected to be a function. Every time JSON tries to convert a value it does not know how to convert it will call the function we passed to it. The function will receive the object in question, and it is expected to return the JSON representation of the object.
def myconverter(o):
if isinstance(o, datetime.datetime):
return o.__str__()
print(json.dumps(d, default = myconverter))
To run the project to latest devices from the older versions of Xcode, follow the following steps :
Go To Finder -> Applications -> Right Click on latest Xcode version -> select show package content -> Developer -> Platforms -> iPhoneOS.platform -> DeviceSupport -> Copy the latest version folder and paste at the same location of your old Xcode i.e in the DeviceSupport folder of your old Xcode.
You can use group by instead of distinct. Because when you use distinct, you'll get struggle to select all values from table. Unlike when you use group by, you can get distinct values and also all fields in table.
Similarly with OUTER JOINs
, the word "OUTER"
is optional. It's the LEFT
or RIGHT
keyword that makes the JOIN
an "OUTER" JOIN
.
However for some reason I always use "OUTER"
as in LEFT OUTER JOIN
and never LEFT JOIN
, but I never use INNER JOIN
, but rather I just use "JOIN"
:
SELECT ColA, ColB, ...
FROM MyTable AS T1
JOIN MyOtherTable AS T2
ON T2.ID = T1.ID
LEFT OUTER JOIN MyOptionalTable AS T3
ON T3.ID = T1.ID
Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:
1. First create a css class
<style type="text/css">
.scrollable{
overflow: auto;
width: 70px; /* adjust this width depending to amount of text to display */
height: 80px; /* adjust height depending on number of options to display */
border: 1px silver solid;
}
.scrollable select{
border: none;
}
</style>
2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.
<div class="scrollable">
<select size="6" multiple="multiple">
<option value="1" selected>option 1 The Long Option</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5 Another Longer than the Long Option ;)</option>
<option value="6">option 6</option>
</select>
</div>
Using python-docx, as @Chinmoy Panda 's answer shows:
for para in doc.paragraphs:
fullText.append(para.text)
However, para.text
will lost the text in w:smarttag
(Corresponding github issue is here: https://github.com/python-openxml/python-docx/issues/328), you should use the following function instead:
def para2text(p):
rs = p._element.xpath('.//w:t')
return u" ".join([r.text for r in rs])
Indeed a one-hot encoder will work just fine here, convert any string and numerical categorical variables you want into 1's and 0's this way and random forest should not complain.
Don't use iterators to do this. Maintain your own loop by incrementing a counter in the callback, and recursively calling the operation on the next item.
$.each(myMap, function(_, arr) {
processArray(arr, 0);
});
function processArray(arr, i) {
if (i >= arr.length) return;
setTimeout(function () {
$('#variant').fadeOut("slow", function () {
$(this).text(i + "-" + arr[i]).fadeIn("slow");
// Handle next iteration
processArray(arr, ++i);
});
}, 6000);
}
Though there's a logic error in your code. You're setting the same container to more than one different value at (roughly) the same time. Perhaps you mean for each one to update its own container.
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
In case somebody needs to append the output and not overriding, it is possible to use "-a" or "--append" option of "tee" command :
ls 2>&1 | tee -a /tmp/ls.txt
ls 2>&1 | tee --append /tmp/ls.txt
Use Simple HTML
<frameset cols="25%,*">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>
$.get("/folder_name/filename.xml", function (xml) {_x000D_
var xmlInnerhtml = xml.documentElement.innerHTML;_x000D_
});
_x000D_
You can use the ScriptEngine
class and evaluate it as a Javascript string.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("4*5");
There may be a better way, but this one works.
This might not be a popular option, but sometimes the scripts end up being distributed in various chunks, in that case I've found this to be a quick fix
if(window.onload != null){var f1 = window.onload;}
window.onload=function(){
//do something
if(f1!=null){f1();}
}
then somewhere else...
if(window.onload != null){var f2 = window.onload;}
window.onload=function(){
//do something else
if(f2!=null){f2();}
}
this will update the onload function and chain as needed
check this as well This gives an overview of associated constraints across a database. Please also include facilitating where condition with table name of interest so gives information faster.
select
a.TABLE_CATALOG as DB_name,a.TABLE_SCHEMA as tbl_schema, a.TABLE_NAME as tbl_name,a. CONSTRAINT_NAME as constraint_name,b.CONSTRAINT_TYPE
from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE a
join INFORMATION_SCHEMA.TABLE_CONSTRAINTS b on
a.CONSTRAINT_NAME=b.CONSTRAINT_NAME
Not sure if this help or not but this is a command line tool which let you simply send test mails from a SMTP server priodically. http://code.google.com/p/woodpecker-tester/
It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress
and the relative URI passed to the GetAsync
method -- or whichever other method of HttpClient
-- only one permutation works. You must place a slash at the end of the BaseAddress
, and you must not place a slash at the beginning of your relative URI, as in the following example.
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://something.com/api/");
var response = await client.GetAsync("resource/7");
}
Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient
.
Run this command to show ip4 and ip6:
ifconfig eth0 | grep inet | awk '{print $2}' | cut -d/ -f1
Prefixing the statement with an exclamation mark will let you know whether the array is not empty. So in your case -
a = [1,2,3]
!a.empty?
=> true
.zone() has been deprecated, and you should use utcOffset instead:
// for a timezone that is +7 UTC hours
moment(1369266934311).utcOffset(420).format('YYYY-MM-DD HH:mm')
I would recommend to use date->diff function, as in example below:
$dStart = new DateTime('2012-07-26');
$dEnd = new DateTime('2012-08-26');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->format('%r%a'); // use for point out relation: smaller/greater
Include a few #ifndef name #define name #endif preprocessor that should solve your problem. The issue is it going from the header to the function then back to the header so it is redefining the class with all the preprocessor(#include) multiple times.
SQL Server Express doesn't include SQL Server Agent, so it's not possible to just create SQL Agent jobs.
What you can do is:
You can create jobs "manually" by creating batch files and SQL script files, and running them via Windows Task Scheduler.
For example, you can backup your database with two files like this:
backup.bat:
sqlcmd -i backup.sql
backup.sql:
backup database TeamCity to disk = 'c:\backups\MyBackup.bak'
Just put both files into the same folder and exeute the batch file via Windows Task Scheduler.
The first file is just a Windows batch file which calls the sqlcmd utility and passes a SQL script file.
The SQL script file contains T-SQL. In my example, it's just one line to backup a database, but you can put any T-SQL inside. For example, you could do some UPDATE
queries instead.
If the jobs you want to create are for backups, index maintenance or integrity checks, you could also use the excellent Maintenance Solution by Ola Hallengren.
It consists of a bunch of stored procedures (and SQL Agent jobs for non-Express editions of SQL Server), and in the FAQ there’s a section about how to run the jobs on SQL Server Express:
How do I get started with the SQL Server Maintenance Solution on SQL Server Express?
SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.
SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.
Download MaintenanceSolution.sql.
Execute MaintenanceSolution.sql. This script creates the stored procedures that you need.
Create cmd files to execute the stored procedures; for example:
sqlcmd -E -S .\SQLEXPRESS -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'USER_DATABASES', @Directory = N'C:\Backup', @BackupType = 'FULL'" -b -o C:\Log\DatabaseBackup.txtIn Windows Scheduled Tasks, create tasks to call the cmd files.
Schedule the tasks.
Start the tasks and verify that they are completing successfully.
You really want to do this
flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))
This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).
Generally speaking an HTTP POST assumes the content of the body contains a series of key/value pairs that are created (most usually) by a form on the HTML side. You don't set the values using setHeader, as that won't place them in the content body.
So with your second test, the problem that you have here is that your client is not creating multiple key/value pairs, it only created one and that got mapped by default to the first argument in your method.
There are a couple of options you can use. First, you could change your method to accept only one input parameter, and then pass in a JSON string as you do in your second test. Once inside the method, you then parse the JSON string into an object that would allow access to the fields.
Another option is to define a class that represents the fields of the input types and make that the only input parameter. For example
class MyInput
{
String str1;
String str2;
public MyInput() { }
// getters, setters
}
@POST
@Consumes({"application/json"})
@Path("create/")
public void create(MyInput in){
System.out.println("value 1 = " + in.getStr1());
System.out.println("value 2 = " + in.getStr2());
}
Depending on the REST framework you are using it should handle the de-serialization of the JSON for you.
The last option is to construct a POST body that looks like:
str1=value1&str2=value2
then add some additional annotations to your server method:
public void create(@QueryParam("str1") String str1,
@QueryParam("str2") String str2)
@QueryParam doesn't care if the field is in a form post or in the URL (like a GET query).
If you want to continue using individual arguments on the input then the key is generate the client request to provide named query parameters, either in the URL (for a GET) or in the body of the POST.
The Groovy script you provided is formatting the first line as a blank line in the resultant script. The shebang, telling the script to run with /bin/bash instead of /bin/sh, needs to be on the first line of the file or it will be ignored.
So instead, you should format your Groovy like this:
stage('Setting the variables values') {
steps {
sh '''#!/bin/bash
echo "hello world"
'''
}
}
And it will execute with /bin/bash.
In ES6 you can use Math.sign function to determine if,
1. its +ve no
2. its -ve no
3. its zero (0)
4. its NaN
console.log(Math.sign(1)) // prints 1
console.log(Math.sign(-1)) // prints -1
console.log(Math.sign(0)) // prints 0
console.log(Math.sign("abcd")) // prints NaN
You can check out this post on SuperUser.
Word starts page numbering over for each new section by default.
I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.
My method:
Format Page Numbers
Continue from Previous Section
radio button under Page numbering
I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.
you can create user and grant privilege
create user read_only identified by read_only; grant create session,select any table to read_only;
Please un check this from the Eclipse Menu.
Run->Skip all breakpoints.
I think this will be enabled permanently once You select the Remove all Break points option in the Debug/Breakpoints window.
I am using angular 4 and faced the same issue apply, all possible solution but finally, this solve my problem
export class AppRoutingModule {
constructor(private router: Router) {
this.router.errorHandler = (error: any) => {
this.router.navigate(['404']); // or redirect to default route
}
}
}
Hope this will help you.
Would've commented on @ianmunoz's post but I don't have enough reputation. You can combine dplyr
's mutate_each
and replace
to take care of the NA
to 0
replacement. Using the dataframe from @aL3xa's answer...
> m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
> d <- as.data.frame(m)
> d
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 4 8 1 9 6 9 NA 8 9 8
2 8 3 6 8 2 1 NA NA 6 3
3 6 6 3 NA 2 NA NA 5 7 7
4 10 6 1 1 7 9 1 10 3 10
5 10 6 7 10 10 3 2 5 4 6
6 2 4 1 5 7 NA NA 8 4 4
7 7 2 3 1 4 10 NA 8 7 7
8 9 5 8 10 5 3 5 8 3 2
9 9 1 8 7 6 5 NA NA 6 7
10 6 10 8 7 1 1 2 2 5 7
> d %>% mutate_each( funs_( interp( ~replace(., is.na(.),0) ) ) )
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 4 8 1 9 6 9 0 8 9 8
2 8 3 6 8 2 1 0 0 6 3
3 6 6 3 0 2 0 0 5 7 7
4 10 6 1 1 7 9 1 10 3 10
5 10 6 7 10 10 3 2 5 4 6
6 2 4 1 5 7 0 0 8 4 4
7 7 2 3 1 4 10 0 8 7 7
8 9 5 8 10 5 3 5 8 3 2
9 9 1 8 7 6 5 0 0 6 7
10 6 10 8 7 1 1 2 2 5 7
We're using standard evaluation (SE) here which is why we need the underscore on "funs_
." We also use lazyeval
's interp
/~
and the .
references "everything we are working with", i.e. the data frame. Now there are zeros!
Your url String needs variable markers for the map you pass to work, like:
String url = "https://app.example.com/hr/email?{email}";
Or you could explicitly code the query params into the String to begin with and not have to pass the map at all, like:
String url = "https://app.example.com/hr/[email protected]";
It's important to point out that all of the above solutions map the port to every interface on your machine. This is less than desirable if you have a public IP address, or your machine has an IP on a large network. Your application may be exposed to a much wider audience than you'd hoped.
redis:
build:
context:
dockerfile: Dockerfile-redis
ports:
- "127.0.0.1:3901:3901"
127.0.0.1
is the ip address that maps to the hostname localhost
on your machine. So now your application is only exposed over that interface and since 127.0.0.1
is only accessible via your machine, you're not exposing your containers to the entire world.
The documentation explains this further and can be found here: https://docs.docker.com/compose/compose-file/#ports
Note: If you're using Docker for mac this will make the container listen on 127.0.0.1 on the Docker for Mac VM and will not be accessible from your localhost. If I recall correctly.
It is an old question but a common one. So let me add this one here.
With arrow function syntax you can achieve it more succinct way since it is lexically binded and can be chained.
An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords.
const event_handler = (event, arg) => console.log(event, arg);
el.addEventListener('click', (event) => event_handler(event, 'An argument'));
If you need to clean up the event listener:
// Let's use use good old function sytax
function event_handler(event, arg) {
console.log(event, arg);
}
// Assign the listener callback to a variable
var doClick = (event) => event_handler(event, 'An argument');
el.addEventListener('click', doClick);
// Do some work...
// Then later in the code, clean up
el.removeEventListener('click', doClick);
Here is crazy one-liner:
// You can replace console.log with some other callback function
el.addEventListener('click', (event) => ((arg) => console.log(event, arg))('An argument'));
More docile version: More appropriate for any sane work.
el.addEventListener('click', (event) => ((arg) => {
console.log(event, arg);
})('An argument'));
For those guys, who are doing it through UMD, and compile via require.js
, there is a laconic solution.
In the module, which requires tether
as the dependency, which loads Tooltip
as UMD, in front of module definition, just put short snippet on definition of Tether:
// First load the UMD module dependency and attach to global scope
require(['tether'], function(Tether) {
// @todo: make it properly when boostrap will fix loading of UMD, instead of using globals
window.Tether = Tether; // attach to global scope
});
// then goes your regular module definition
define([
'jquery',
'tooltip',
'popover'
], function($, Tooltip, Popover){
"use strict";
//...
/*
by this time, you'll have window.Tether global variable defined,
and UMD module Tooltip will not throw the exception
*/
//...
});
This short snippet at the very beginning, actually may be put on any higher level of your application, the most important thing - to invoke it before actual usage of bootstrap
components with Tether
dependency.
// ===== file: tetherWrapper.js =====
require(['./tether'], function(Tether) {
window.Tether = Tether; // attach to global scope
// it's important to have this, to keep original module definition approach
return Tether;
});
// ===== your MAIN configuration file, and dependencies definition =====
paths: {
jquery: '/vendor/jquery',
// tether: '/vendor/tether'
tether: '/vendor/tetherWrapper' // @todo original Tether is replaced with our wrapper around original
// ...
},
shim: {
'bootstrap': ['tether', 'jquery']
}
UPD: In Boostrap 4.1 Stable they replaced Tether, with Popper.js, see the documentation on usage.
Solutions above didn't work. It simply displayed the last key/value pairs, but this did:
http://localhost/?key[]=1&key[]=2
Returns:
Array
(
[key] => Array
(
[0] => 1
[1] => 2
)
I believe that using "cbind" is the simplest way to add a column to a data frame in R. Below an example:
myDf = data.frame(index=seq(1,10,1), Val=seq(1,10,1))
newCol= seq(2,20,2)
myDf = cbind(myDf,newCol)
I tried all of above, nothing worked. What resolved the issue was adding IPv6 bindings in the hosts file. In step 5 of @David Murdochs answer, add two lines instead of one, i.e.:
127.0.0.1 dev.example.com
::1 dev.example.com
I figured it out by checking $ ping localhost
from command line, which used to return:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Instead, it now returns:
Reply from ::1: time<1ms
I don't know why, but for some reason IIS Express started using IPv6 instead of IPv4.
Bootstrap has text-center to center a text. For example
<div class="container text-center">
You change the following
<div class="row justify-content-center align-items-center">
to the following
<div class="row text-center">
You need to have a smtp service setup in your local machine in order to send emails. There are many available freely just search on google.
If you own a server or VPS upload the script and it will work fine.
You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:
In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file"
field, ostensibly for backward compatibility reasons.
So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.
The WITH syntax appears to be valid in an inline view, e.g.
UPDATE (WITH comp AS ...
SELECT SomeColumn, ComputedValue FROM t INNER JOIN comp ...)
SET SomeColumn=ComputedValue;
But in the quick tests I did this always failed with ORA-01732: data manipulation operation not legal on this view
, although it succeeded if I rewrote to eliminate the WITH clause. So the refactoring may interfere with Oracle's ability to guarantee key-preservation.
You should be able to use a MERGE, though. Using the simple example you've posted this doesn't even require a WITH clause:
MERGE INTO mytable t
USING (select *, 42 as ComputedValue from mytable where id = 1) comp
ON (t.id = comp.id)
WHEN MATCHED THEN UPDATE SET SomeColumn=ComputedValue;
But I understand you have a more complex subquery you want to factor out. I think that you will be able to make the subquery in the USING
clause arbitrarily complex, incorporating multiple WITH
clauses.
Can't load library: /home/tom/.swt/lib/linux/x86_64/libswt-gtk-3740.so Can't load library: /home/tom/.swt/lib/linux/x86_64/libswt-gtk.so
looks like the libraries should be at .swt/lib/linux/x86_64/ if there are not there you can try this command:
locate libswt-gtk.so
this should find the libraries copy the entire directory to /home/tom/.swt/lib/linux/x86_64
If you don't want to create a new dataframe, or if your dataframe has more columns than just the ones you want to split, you could:
df["flips"], df["row_name"] = zip(*df["row"].str.split().tolist())
del df["row"]
You can fix this issue using the binding from How to generate @XmlRootElement Classes for Base Types in XSD?.
Here is an example with Maven
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.3.1</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaDirectory>src/main/resources/xsd</schemaDirectory>
<packageName>com.mycompany.schemas</packageName>
<bindingFiles>bindings.xjb</bindingFiles>
<extension>true</extension>
</configuration>
</plugin>
Here is the binding.xjb
file content
<?xml version="1.0"?>
<jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc= "http://java.sun.com/xml/ns/jaxb/xjc"
jxb:extensionBindingPrefixes="xjc" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<jxb:bindings schemaLocation="path/to/myschema.xsd" node="/xs:schema">
<jxb:globalBindings>
<xjc:simple/>
</jxb:globalBindings>
</jxb:bindings>
</jxb:bindings>
You should remove navbar-fixed-top
class otherwise navbar stays fixed on top of page where you want logo.
If you want to place logo inside navbar:
Navbar height (set in @navbarHeight
LESS variable) is 40px
by default. Your logo has to fit inside or you have to make navbar higher first.
Then use brand
class:
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a href="/" class="brand"><img alt="" src="/logo.gif" /></a>
</div>
</div>
</div>
If your logo is higher than 20px
, you have to fix stylesheets as well.
If you do that in LESS:
.navbar .brand {
@elementHeight: 32px;
padding: ((@navbarHeight - @elementHeight) / 2 - 2) 20px ((@navbarHeight - @elementHeight) / 2 + 2);
}
@elementHeight
should be set to your image height.
Padding calculation is taken from Twitter Bootstrap LESS - https://github.com/twitter/bootstrap/blob/v2.0.4/less/navbar.less#L51-52
Alternatively you can calculate padding values yourself and use pure CSS.
This works for Twitter Bootstrap versions 2.0.x, should work in 2.1 as well, but padding calculation was changed a bit: https://github.com/twitter/bootstrap/blob/v2.1.0/less/navbar.less#L50
You can use below to find a particular trigger definition.
SHOW TRIGGERS LIKE '%trigger_name%'\G
or the below to show all the triggers in the database. It will work for MySQL 5.0 and above.
SHOW TRIGGERS\G
Try the following in your view to check the output from each. The first one updates when the view is called a second time. My controller uses the key ShowCreateButton and has the optional parameter _createAction with a default value - you can change this to your key/parameter
@Html.TextBox("_createAction", null, new { Value = (string)ViewBag.ShowCreateButton })
@Html.TextBox("_createAction", ViewBag.ShowCreateButton )
@ViewBag.ShowCreateButton
For me, my issue was that I was
android:background="?attr/selectableItemBackground"
To a LinearLayout background, once I removed it the test passed.
The easiest way is to just learn how to do DOM traversing and manipulation with the plain DOM api (you would probably call this: normal JavaScript).
This can however be a pain for some things. (which is why libraries were invented in the first place).
Googling for "javascript DOM traversing/manipulation" should present you with plenty of helpful (and some less helpful) resources.
The articles on this website are pretty good: http://www.htmlgoodies.com/primers/jsp/
And as Nosredna points out in the comments: be sure to test in all browsers, because now jQuery won't be handling the inconsistencies for you.
function selectedValues(ele){_x000D_
var arr = [];_x000D_
for(var i = 0; i < ele.length; i++){_x000D_
if(ele[i].type == 'checkbox' && ele[i].checked){_x000D_
arr.push(ele[i].value);_x000D_
}_x000D_
}_x000D_
return arr;_x000D_
}
_x000D_
Why don't you simply use set_index
method?
In : col = ['a','b','c']
In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
In : data
Out:
a b c
0 1 2 3
1 10 11 12
2 20 21 22
In : data2 = data.set_index('a')
In : data2
Out:
b c
a
1 2 3
10 11 12
20 21 22
If you're up for it, use the DateTime class
I have used both JXL (now "JExcel") and Apache POI. At first I used JXL, but now I use Apache POI.
First, here are the things where both APIs have the same end functionality:
However, there are many differences:
Additionally, POI contains not just the main "usermodel" API, but also an event-based API if all you want to do is read the spreadsheet content.
In conclusion, because of the better documentation, more features, active development, and Excel 2007+ format support, I use Apache POI.
To supplement the above answers into something a little more re-usable, I've come up with this, which continues to prompt the user if the input is considered invalid.
try:
input = raw_input
except NameError:
pass
def prompt(message, errormessage, isvalid):
"""Prompt for input given a message and return that value after verifying the input.
Keyword arguments:
message -- the message to display when asking the user for the value
errormessage -- the message to display when the value fails validation
isvalid -- a function that returns True if the value given by the user is valid
"""
res = None
while res is None:
res = input(str(message)+': ')
if not isvalid(res):
print str(errormessage)
res = None
return res
It can be used like this, with validation functions:
import re
import os.path
api_key = prompt(
message = "Enter the API key to use for uploading",
errormessage= "A valid API key must be provided. This key can be found in your user profile",
isvalid = lambda v : re.search(r"(([^-])+-){4}[^-]+", v))
filename = prompt(
message = "Enter the path of the file to upload",
errormessage= "The file path you provided does not exist",
isvalid = lambda v : os.path.isfile(v))
dataset_name = prompt(
message = "Enter the name of the dataset you want to create",
errormessage= "The dataset must be named",
isvalid = lambda v : len(v) > 0)
${#str_var}
where str_var
is your string.
The executable used to run batch scripts is cmd.exe
which uses the /c
flag to specify the name of the batch file to run:
Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", "build.bat"});
Theoretically you should also be able to run Scons in this manner, though I haven't tested this:
Runtime.getRuntime().exec(new String[]{"scons", "-Q", "implicit-deps-changed", "build\file_load_type", "export\file_load_type"});
EDIT: Amara, you say that this isn't working. The error you listed is the error you'd get when running Java from a Cygwin terminal on a Windows box; is this what you're doing? The problem with that is that Windows and Cygwin have different paths, so the Windows version of Java won't find the scons executable on your Cygwin path. I can explain further if this turns out to be your problem.
Try to use it:
Drop-down box dependent on the option selected in another drop-down box. Use jQuery to change a second select list based on the first select list option.
<asp:HiddenField ID="hdfServiceId" ClientIDMode="Static" runat="server" Value="0" />
<asp:TextBox ID="txtOfferId" CssClass="hidden" ClientIDMode="Static" runat="server" Text="0" />
<asp:HiddenField ID="SelectedhdfServiceId" ClientIDMode="Static" runat="server" Value="0" />
<asp:HiddenField ID="SelectedhdfOfferId" ClientIDMode="Static" runat="server" Value="0" />
<div class="col-lg-2 col-md-2 col-sm-12">
<span>Service</span>
<asp:DropDownList ID="ddlService" ClientIDMode="Static" runat="server" CssClass="form-control">
</asp:DropDownList>
</div>
<div class="col-lg-2 col-md-2 col-sm-12">
<span>Offer</span>
<asp:DropDownList ID="ddlOffer" ClientIDMode="Static" runat="server" CssClass="form-control">
</asp:DropDownList>
</div>
Use jQuery library in your web page.
<script type="text/javascript">
$(document).ready(function () {
ucBindOfferByService();
$("#ddlOffer").val($('#txtOfferId').val());
});
$('#ddlOffer').on('change', function () {
$("#txtOfferId").val($('#ddlOffer').val());
});
$('#ddlService').on('change', function () {
$("#SelectedhdfOfferId").val("0");
SetServiceIds();
var SelectedServiceId = $('#ddlService').val();
$("#SelectedhdfServiceId").val(SelectedServiceId);
if (SelectedServiceId == '0') {
}
ucBindOfferByService();
SetOfferIds();
});
function ucBindOfferByService() {
GetVendorOffer();
var SelectedServiceId = $('#ddlService').val();
if (SelectedServiceId == '0') {
$("#ddlOffer").empty();
$("#ddlOffer").append($("<option></option>").val("0").html("All"));
}
else {
$("#ddlOffer").empty();
$(document.ucVendorServiceList).each(function () {
if ($("#ddlOffer").html().length == "0") {
$("#ddlOffer").append($("<option></option>").val("0").html("All"));
}
$("#ddlOffer").append($("<option></option>").val(this.OfferId).html(this.OfferName));
});
}
}
function GetVendorOffer() {
var param = JSON.stringify({ UserId: $('#hdfUserId').val(), ServiceId: $('#ddlService').val() });
AjaxCall("DemoPage.aspx", "GetOfferList", param, OnGetOfferList, AjaxCallError);
}
function OnGetOfferList(response) {
if (response.d.length > 0)
document.ucVendorServiceList = JSON.parse(response.d);
}
function SetServiceIds() {
var SelectedServiceId = $('#ddlService').val();
var ServiceIdCSV = ',';
if (SelectedServiceId == '0') {
$('#ddlService > option').each(function () {
ServiceIdCSV += $(this).val() + ',';
});
}
else {
ServiceIdCSV += SelectedServiceId + ',';
}
$("#hdfServiceId").val(ServiceIdCSV);
}
function SetOfferIds() {
var SelectedServiceId = $('#ddlService').val();
var OfferIdCSV = ',';
if (SelectedServiceId == '0') {
$(document.ucVendorServiceList).each(function () {
OfferIdCSV += this.OfferId + ',';
});
}
else {
var SelectedOfferId = $('#ddlOffer').val();
if (SelectedOfferId == "0") {
$('#ddlOffer > option').each(function () {
OfferIdCSV += $(this).val() + ',';
});
}
else {
OfferIdCSV += SelectedOfferId + ',';
}
}
}
</script>
Use Backend code in your web page.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ServiceList();
}
}
public void ServiceList()
{
ManageReport manageReport = new ManageReport();
DataTable ServiceList = new DataTable();
ServiceList = manageReport.GetServiceList();
ddlService.DataSource = ServiceList;
ddlService.DataTextField = "serviceName";
ddlService.DataValueField = "serviceId";
ddlService.DataBind();
ddlService.Items.Insert(0, new ListItem("All", "0"));
}
public DataTable GetServiceList()
{
SqlParameter[] PM = new SqlParameter[]
{
new SqlParameter("@Mode" ,"Mode_Name" ),
new SqlParameter("@UserID" ,UserId )
};
return SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, "Sp_Name", PM).Tables[0];
}
[WebMethod]
public static String GetOfferList(int UserId, String ServiceId)
{
var sOfferList = "";
try
{
CommonUtility utility = new CommonUtility();
ManageReport manageReport = new ManageReport();
manageReport.UserId = UserId;
manageReport.ServiceId = ServiceId;
DataSet dsOfferList = manageReport.GetOfferList();
if (utility.ValidateDataSet(dsOfferList))
{
//DataRow dr = dsEmployerUserDepartment.Tables[0].NewRow();
//dr[0] = "0";
// dr[1] = "All";
//dsEmployerUserDepartment.Tables[0].Rows.InsertAt(dr, 0);
sOfferList = utility.ConvertToJSON(dsOfferList.Tables[0]);
}
return sOfferList;
}
catch (Exception ex)
{
return "Error Message: " + ex.Message;
}
}
public DataSet GetOfferList()
{
SqlParameter[] sqlParameter = new SqlParameter[]
{
new SqlParameter("@Mode" ,"Mode_Name" ),
new SqlParameter("@UserID" ,UserId ),
new SqlParameter("@ServiceId" ,ServiceId )
};
return SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, "Sp_Name", sqlParameter);
}
To loop through JSON Object : In Angluar's (6.0.0+), now they provide the pipe keyvalue
:
<div *ngFor="let item of object| keyvalue">
{{ item.key }} - {{ item.value }}
</div>
To just display JSON
{{ object | json }}
create a class create a object globally and call this
using System.IO;
using System.Reflection;
public class LogWriter
{
private string m_exePath = string.Empty;
public LogWriter(string logMessage)
{
LogWrite(logMessage);
}
public void LogWrite(string logMessage)
{
m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
try
{
using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
{
Log(logMessage, w);
}
}
catch (Exception ex)
{
}
}
public void Log(string logMessage, TextWriter txtWriter)
{
try
{
txtWriter.Write("\r\nLog Entry : ");
txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
txtWriter.WriteLine(" :");
txtWriter.WriteLine(" :{0}", logMessage);
txtWriter.WriteLine("-------------------------------");
}
catch (Exception ex)
{
}
}
}
Caveat Emptor - Destructive commands ahead.
Mitigation - git reflog
can save you if you need it.
1) UNDO local file changes and KEEP your last commit
git reset --hard
2) UNDO local file changes and REMOVE your last commit
git reset --hard HEAD^
3) KEEP local file changes and REMOVE your last commit
git reset --soft HEAD^
I like Andy's answer, but the id isn't going to necessarily be unique, so here's what I came up with to create a unique ID also. Can be checked at jsfiddle too. Please note that arr.length + 1
may very well not guarantee a unique ID if anything had been removed previously.
var array = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' } ];
var usedname = 'bill';
var newname = 'sam';
// don't add used name
console.log('before usedname: ' + JSON.stringify(array));
tryAdd(usedname, array);
console.log('before newname: ' + JSON.stringify(array));
tryAdd(newname, array);
console.log('after newname: ' + JSON.stringify(array));
function tryAdd(name, array) {
var found = false;
var i = 0;
var maxId = 1;
for (i in array) {
// Check max id
if (maxId <= array[i].id)
maxId = array[i].id + 1;
// Don't need to add if we find it
if (array[i].username === name)
found = true;
}
if (!found)
array[++i] = { id: maxId, username: name };
}
The instantclient works only by defining the folder in the windows PATH environment variable. But you can "install" manually to create some keys in the Windows registry. How?
1) Download instantclient (http://www.oracle.com/technetwork/topics/winsoft-085727.html)
2) Unzip the ZIP file (eg c:\oracle\instantclient).
3) Include the above path in the PATH.
4) Create the registry key:
[HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE]
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE]
5) In the above registry key, create a sub-key starts with "KEY_" followed by the name of the installation you want:
[HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_INSTANTCLIENT]
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE\KEY_INSTANTCLIENT]
6) Now create at least three string values ??in the above key:
NLS_LANG = BRAZILIAN PORTUGUESE_BRAZIL.WE8MSWIN1252
(complete list here: http://docs.oracle.com/cd/B19306_01/install.102/b14317/gblsupp.htm)ORACLE_HOME = c:\oracle\instantclient
(the same folder in PATH)ORACLE_HOME_NAME = MY_INSTANTCLIENT
(choose any name)For those who use Quest SQL Navigator or Quest Toad for Oracle will see that it works. Displays the message "Home is valid.":
The registry keys are now displayed for selecting the oracle client:
As mentioned in several places, I'm also not able to get the req.session.destroy() function to work correctly.
This is my work around .. seems to do the trick, and still allows req.flash to be used
req.session = {};
If you delete or set req.session = null; , seems then you can't use req.flash
I've got this problem when I use HttpClient in Multithread envirnoment (Servlets). One servlet still holds connection and another one want to get connection.
Solution:
version 4.0 use ThreadSafeClientConnManager
version 4.2 use PoolingClientConnectionManager
and set this two setters:
setDefaultMaxPerRoute
setMaxTotal
List is just an interface. The question is: is your actual List implementation serializable? Speaking about the standard List implementations (ArrayList, LinkedList) from the Java run-time, most of them actually are already.
$(document).height() seems to do the trick and gives the total height including the area which is only visible through scrolling.
EDIT:
If you don't need to support IE10, you can simply use: document.location.origin
Original answer, if you need legacy support
You can get all this and more by inspecting the location object:
location = {
host: "stackoverflow.com",
hostname: "stackoverflow.com",
href: "http://stackoverflow.com/questions/2300771/jquery-domain-get-url",
pathname: "/questions/2300771/jquery-domain-get-url",
port: "",
protocol: "http:"
}
so:
location.host
would be the domain, in this case stackoverflow.com. For the complete first part of the url, you can use:
location.protocol + "//" + location.host
which in this case would be http://stackoverflow.com
No jQuery required.
Look this http://iswift.org/cookbook/compare-2-dates
Get Dates:
// Get current date
let dateA = NSDate()
// Get a later date (after a couple of milliseconds)
let dateB = NSDate()
Using SWITCH Statement
// Compare them
switch dateA.compare(dateB) {
case .OrderedAscending : print("Date A is earlier than date B")
case .OrderedDescending : print("Date A is later than date B")
case .OrderedSame : print("The two dates are the same")
}
using IF Statement
if dateA.compare(dateB) == .orderedAscending {
datePickerTo.date = datePicker.date
}
//OR
if case .orderedAcending = dateA.compare(dateB) {
}
You can implicitly convert between numerical types, even when that loses precision:
char c = i;
However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use static_cast
for the conversion.
Of the other casts:
dynamic_cast
only works for pointers or references to polymorphic class types;const_cast
can't change types, only const
or volatile
qualifiers;reinterpret_cast
is for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won't do numeric conversions.static_cast
, const_cast
and reinterpret_cast
is needed to get the job done.A static library gets compiled into the client. A .lib is used at compile time and the contents of the library become part of the consuming executable.
A dynamic library is loaded at runtime and not compiled into the client executable. Dynamic libraries are more flexible as multiple client executables can load a DLL and utilize its functionality. This also keeps the overall size and maintainability of your client code to a minimum.
doAnswer
and thenReturn
do the same thing if:
Let's mock this BookService
public interface BookService {
String getAuthor();
void queryBookTitle(BookServiceCallback callback);
}
You can stub getAuthor() using doAnswer
and thenReturn
.
BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return "Joshua";
}
}).when(service).getAuthor();
Note that when using doAnswer
, you can't pass a method on when
.
// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());
So, when would you use doAnswer
instead of thenReturn
? I can think of two use cases:
Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.
BookServiceCallback callback = new BookServiceCallback() {
@Override
public void onSuccess(String bookTitle) {
assertEquals("Effective Java", bookTitle);
}
};
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
callback.onSuccess("Effective Java");
// return null because queryBookTitle is void
return null;
}
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:
List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));
Using doAnswer we can stub it safely.
List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));
Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn
.
List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));
#!/usr/bin/env sh
# Searches a subset string in a string:
# 1st arg:reference string
# 2nd arg:subset string to be matched
if echo "$1" | grep -q "$2"
then
echo "$2 is in $1"
else
echo "$2 is not in $1"
fi
(As of Xcode Version 12)
I'm not sure if the original poster meant the background color of the entire screen or of individual views. So I'll just add this answer which is to set the entire screen's background color.
var body: some View {
ZStack {
Color.purple
.ignoresSafeArea()
// Your other content here
// Other layers will respect the safe area edges
}
}
I added .ignoresSafeArea()
otherwise, it will stop at safe area margins.
var body: some View {
Color.purple
.ignoresSafeArea(.vertical) // Ignore just for the color
.overlay(
VStack(spacing: 20) {
Text("Overlay").font(.largeTitle)
Text("Example").font(.title).foregroundColor(.white)
})
}
Note: It's important to keep the .ignoresSafeArea
on just the color so your main content isn't ignoring the safe area edges too.
Use sed to remove the duplicate user ID, assuming user IDs do not contain any spaces.
awk -F, '{ print $3, $0 }' user.csv | sort | sed 's/^.* //'
LATE EDIT: Starting with Java 8 you should use neither java.util.Date
nor java.sql.Date
if you can at all avoid it, and instead prefer using the java.time
package (based on Joda) rather than anything else. If you're not on Java 8, here's the original response:
java.sql.Date
- when you call methods/constructors of libraries that use it (like JDBC). Not otherwise. You don't want to introduce dependencies to the database libraries for applications/modules that don't explicitly deal with JDBC.
java.util.Date
- when using libraries that use it. Otherwise, as little as possible, for several reasons:
It's mutable, which means you have to make a defensive copy of it every time you pass it to or return it from a method.
It doesn't handle dates very well, which backwards people like yours truly, think date handling classes should.
Now, because j.u.D doesn't do it's job very well, the ghastly Calendar
classes were introduced. They are also mutable, and awful to work with, and should be avoided if you don't have any choice.
There are better alternatives, like the Joda Time API (which might even make it into Java 7 and become the new official date handling API - a quick search says it won't).
If you feel it's overkill to introduce a new dependency like Joda, long
s aren't all that bad to use for timestamp fields in objects, although I myself usually wrap them in j.u.D when passing them around, for type safety and as documentation.
latest
is really designed to work with date fields (it probably does work with other total-ordered types too, but not sure). And the only way you can use it without specifying the field name is by setting the get_latest_by
meta attribute, as mentioned here.
If anybody still wants this, Java regex for support Unicode? is a good one. It's for when you want ONLY letters (no matter what encoding - japaneese, sweedish) iside an EditText. Later, you can check it using Matcher
and Pattern.compile()
final Map<String, String> mss1 = new ProcessBuilder().environment();
mss1.entrySet()
.stream()
//depending on how you want to join K and V use different delimiter
.map(entry ->
String.join(":", entry.getKey(),entry.getValue()))
.forEach(System.out::println);
$(".overdue").each( function() {
alert("Your book is overdue.");
});
Note that ".addClass()" works because addClass is a function defined on the jQuery object. You can't just plop any old function on the end of a selector and expect it to work.
Also, probably a bad idea to bombard the user with n popups (where n = the number of books overdue).
Perhaps use the size function:
alert( "You have " + $(".overdue").size() + " books overdue." );
Note: this answer is only valid for git v1.8 and older.
Most of this has been said in the other answers and comments, but here's a concise explanation:
git fetch
fetches all branch heads (or all specified by the remote.fetch config option), all commits necessary for them, and all tags which are reachable from these branches. In most cases, all tags are reachable in this way.git fetch --tags
fetches all tags, all commits necessary for them. It will not update branch heads, even if they are reachable from the tags which were fetched.Summary: If you really want to be totally up to date, using only fetch, you must do both.
It's also not "twice as slow" unless you mean in terms of typing on the command-line, in which case aliases solve your problem. There is essentially no overhead in making the two requests, since they are asking for different information.
it stands for your website where your app is running on. like you have made an app www.xyz.pqr then you will type this www.xyz.pqr in App domain the site where your app is running on should be secure and valid
The answer is technically neither. According to the Java Virtual Machine Specification, the area for storing string literals is in the runtime constant pool. The runtime constant pool memory area is allocated on a per-class or per-interface basis, so it's not tied to any object instances at all. The runtime constant pool is a subset of the method area which "stores per-class structures such as the runtime constant pool, field and method data, and the code for methods and constructors, including the special methods used in class and instance initialization and interface type initialization". The VM spec says that although the method area is logically part of the heap, it doesn't dictate that memory allocated in the method area be subject to garbage collection or other behaviors that would be associated with normal data structures allocated to the heap.
You can pipe the source string to findstr
and check the value of ERRORLEVEL
to see if the pattern string was found. A value of zero indicates success and the pattern was found. Here is an example:
::
: Y.CMD - Test if pattern in string
: P1 - the pattern
: P2 - the string to check
::
@echo off
echo.%2 | findstr /C:"%1" 1>nul
if errorlevel 1 (
echo. got one - pattern not found
) ELSE (
echo. got zero - found pattern
)
When this is run in CMD.EXE, we get:
C:\DemoDev>y pqrs "abc def pqr 123"
got one - pattern not found
C:\DemoDev>y pqr "abc def pqr 123"
got zero - found pattern
Instant
corresponds to time on the prime meridian (Greenwich).
Whereas LocalDateTime
relative to OS time zone settings, and
cannot represent an instant without additional information such as an offset or time-zone.
Possible solution is described in this Code Project tip:
As folks mentioned IIS user network service user credentials while trying to log in sql server. So just change the Application pool settings in your IIS:
- Open Internet Information Service Manager
- Click on Application Pools in left navigation tree.
- Select your version Pool. In my case, I am using ASP .Net v4.0. If you dont have this version, select DefaultAppPool.
- Right click on step 3, and select advanced settings.
- Select Identity in properties window and click the button to change the value.
- Select Local System in Built-in accounts combo box and click ok. That's it. Now run your application. Everything works well.
In python, not
is a boolean operator which gets the opposite of a value:
>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False
And True == 1
and False == 0
(if you need to convert it to an integer, you can use int()
)
If you need to retrieve more columns other than columns which are in group by then you can consider below query. Check it once whether it is performing well or not.
SELECT
a.[CUSTOMER ID],
a.[NAME],
(select SUM(b.[AMOUNT]) from INV_DATA b
where b.[CUSTOMER ID] = a.[CUSTOMER ID]
GROUP BY b.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA a
You can use below code to initialize size and set empty value to array of Strings
String[] row = new String[size];
Arrays.fill(row, "");
You need a root node
<?xml version="1.0" encoding="ISO-8859-1"?>
<documents>
<document>
<name>Sample Document</name>
<type>document</type>
<url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&titletype=Title&fontsize=9&fontface=Arial&spacing=1.0&text=&wordcount3=0</url>
</document>
<document>
<name>Sample</name>
<type>document</type>
<url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&titletype=Title&fontsize=9&fontface=Arial&spacing=1.0&text=&</url>
</document>
</documents>
I like Greg solution, but I wish it was more python like. I feel it would be faster and more readable; so after some time of coding I came out with this.
The first two functions are needed to make the cartesian product of lists. And can be reused whnever this problem arises. By the way, I had to program this myself, if anyone knows of a standard solution for this problem, please feel free to contact me.
"Factorgenerator" now returns a dictionary. And then the dictionary is fed into "divisors", who uses it to generate first a list of lists, where each list is the list of the factors of the form p^n with p prime. Then we make the cartesian product of those lists, and we finally use Greg' solution to generate the divisor. We sort them, and return them.
I tested it and it seem to be a bit faster than the previous version. I tested it as part of a bigger program, so I can't really say how much is it faster though.
Pietro Speroni (pietrosperoni dot it)
from math import sqrt
##############################################################
### cartesian product of lists ##################################
##############################################################
def appendEs2Sequences(sequences,es):
result=[]
if not sequences:
for e in es:
result.append([e])
else:
for e in es:
result+=[seq+[e] for seq in sequences]
return result
def cartesianproduct(lists):
"""
given a list of lists,
returns all the possible combinations taking one element from each list
The list does not have to be of equal length
"""
return reduce(appendEs2Sequences,lists,[])
##############################################################
### prime factors of a natural ##################################
##############################################################
def primefactors(n):
'''lists prime factors, from greatest to smallest'''
i = 2
while i<=sqrt(n):
if n%i==0:
l = primefactors(n/i)
l.append(i)
return l
i+=1
return [n] # n is prime
##############################################################
### factorization of a natural ##################################
##############################################################
def factorGenerator(n):
p = primefactors(n)
factors={}
for p1 in p:
try:
factors[p1]+=1
except KeyError:
factors[p1]=1
return factors
def divisors(n):
factors = factorGenerator(n)
divisors=[]
listexponents=[map(lambda x:k**x,range(0,factors[k]+1)) for k in factors.keys()]
listfactors=cartesianproduct(listexponents)
for f in listfactors:
divisors.append(reduce(lambda x, y: x*y, f, 1))
divisors.sort()
return divisors
print divisors(60668796879)
P.S. it is the first time I am posting to stackoverflow. I am looking forward for any feedback.
You have mostly the right idea, it's just the sending of the form that is wrong. The form belongs in the body of the request.
req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))
My example code was correct and the issue was something else in my actual code. Still, I know it was difficult to find examples of this so I'm answering it in case someone else is looking.
<div ng-repeat="f in foos">
<div>
<div ng-repeat="b in foos.bars">
<a ng-click="addSomething($parent.$index)">Add Something</a>
</div>
</div>
</div>
The keyword you're looking for is super
. See this guide, for instance.
I think important to emphasize - using Except method will return you items who are in the first without the items in the second one only. It does not return those elements in second that do not appear in first.
var list1 = new List<int> { 1, 2, 3, 4, 5};
var list2 = new List<int> { 3, 4, 5, 6, 7 };
var list3 = list1.Except(list2).ToList(); //list3 contains only 1, 2
But if you want get real difference between two lists:
Items who are in the first without the items in the second one and items who are in the second without the items in the first one.
You need using Except twice:
var list1 = new List<int> { 1, 2, 3, 4, 5};
var list2 = new List<int> { 3, 4, 5, 6, 7 };
var list3 = list1.Except(list2); //list3 contains only 1, 2
var list4 = list2.Except(list1); //list4 contains only 6, 7
var resultList = list3.Concat(list4).ToList(); //resultList contains 1, 2, 6, 7
Or you can use SymmetricExceptWith method of HashSet. But it changes the set on which called:
var list1 = new List<int> { 1, 2, 3, 4, 5};
var list2 = new List<int> { 3, 4, 5, 6, 7 };
var list1Set = list1.ToHashSet(); //.net framework 4.7.2 and .net core 2.0 and above otherwise new HashSet(list1)
list1Set.SymmetricExceptWith(list2);
var resultList = list1Set.ToList(); //resultList contains 1, 2, 6, 7
I was trying to copy the size data measured from Chrome Network and stumbled on this post. I just found an easier way to "export" the data out to excel which is to copy the table and paste to excel.
The trick is click Control + A (select all) and once the entire table will be highlighted, paste it to Microsoft Excel. The only issue is if there are too many fields, not all rows are copied and you might have to copy and paste several times.
UPDATED: I found that copying the data only works when I turn off the filter options (the funnel-looking button above the table). – bendur
None of these worked for me, except for this. My site was hosted in https://www.asmallorange.com
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteCond %{SERVER_PORT} !^443$
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Here's how I download CSV files on the client side in my Java GWT application. Special thanks to Xavier John for his solution. It's been verified to work in FF 24.6.0, IE 11.0.20, and Chrome 45.0.2454.99 (64-bit). I hope this saves someone a bit of time:
public class ExportFile
{
private static final String CRLF = "\r\n";
public static void exportAsCsv(String filename, List<List<String>> data)
{
StringBuilder sb = new StringBuilder();
for(List<String> row : data)
{
for(int i=0; i<row.size(); i++)
{
if(i>0) sb.append(",");
sb.append(row.get(i));
}
sb.append(CRLF);
}
generateCsv(filename, sb.toString());
}
private static native void generateCsv(String filename, String text)
/*-{
var blob = new Blob([text], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) // IE 10+
{
navigator.msSaveBlob(blob, filename);
}
else
{
var link = document.createElement("a");
if (link.download !== undefined) // feature detection
{
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}-*/;
}
Try =index(ARRAY, ROW, COLUMN)
where: Array: select the whole sheet Row, Column: Your row and column references
That should be easier to understand to those looking at the formula.
You must be providing the wrong path to the debug.keystore
file.
Follow these steps to get the correct path and complete your command:
And finally, use the path you just copied from Step 3 to construct your command:
For example, in my case, it would be:
C:\Program Files\Java\jre7\bin>keytool -list -v -keystore "C:\Users\Siddharth Lele.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
UPDATED:
If you had already followed the steps mentioned above, the only other solution is to delete the debug.keystore
and let Eclipse recreate it for you.
Step 1: Go to the path where your keystore is stored. In your case, C:\Users\Suresh\.android\debug.keystore
Step 2: Close and restart Eclipse.
Step 3 (Optional): You may need to clean your project before the debug.keystore
is created again.
Source: http://www.coderanch.com/t/440920/Security/KeyTool-genkeypair-exception-Keystore-file
You can refer to this for the part about deleting your debug.keystore
file: "Debug certificate expired" error in Eclipse Android plugins
Open the pom.xml file.
under the project
tag add <dependencies>
as another tag, and google for the Maven dependencies. I used this to search.
So after getting the dependency create another tag dependency
inside <dependencies>
tag.
So ultimately it will look something like this.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>doc-examples</groupId>
<artifactId>lambda-java-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>lambda-java-example</name>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-lambda-java-core -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</project>
Hope it helps.
You might be better off using a ListView with a CursorAdapter (or SimpleCursorAdapter).
These are built to show rows from a sqlite database and allow refreshing with minimal programming on your part.
Edit - here is a tutorial involving SimpleCursorAdapter and ListView including sample code.
I will suggest move all templates to separate files, and don't do spagetti inside repeat
take a look here:
html:
<div ng-repeat = "data in comments">
<div ng-include src="buildUrl(data.type)"></div>
</div>
js:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.comments = [
{"_id":"52fb84fac6b93c152d8b4569",
"post_id":"52fb84fac6b93c152d8b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"hoot"},
{"_id":"52fb798cc6b93c74298b4568",
"post_id":"52fb798cc6b93c74298b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"story"},
{"_id":"52fb7977c6b93c5c2c8b456b",
"post_id":"52fb7977c6b93c5c2c8b456a",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"article"}
];
$scope.buildUrl = function(type) {
return type + '.html';
}
});
Your new environment may have E_STRICT
warnings enabled in error_reporting
for PHP versions <= 5.3.x, or simply have error_reporting
set to at least E_WARNING
with PHP versions >= 5.4. That error is triggered when $res
is NULL
or not yet initialized:
$res = NULL;
$res->success = false; // Warning: Creating default object from empty value
PHP will report a different error message if $res
is already initialized to some value but is not an object:
$res = 33;
$res->success = false; // Warning: Attempt to assign property of non-object
In order to comply with E_STRICT
standards prior to PHP 5.4, or the normal E_WARNING
error level in PHP >= 5.4, assuming you are trying to create a generic object and assign the property success
, you need to declare $res
as an object of stdClass
in the global namespace:
$res = new \stdClass();
$res->success = false;
Equivalently to Jena's solution:
>>> l=[[1,2,3],[4,5,6],[7,8,9]]
>>> [list(i) for i in zip(*l)]
... [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
According to the Stacktrace
Exception in thread "main" java.lang.NullPointerException
at java.util.HashMap.merge(HashMap.java:1216)
at java.util.stream.Collectors.lambda$toMap$148(Collectors.java:1320)
at java.util.stream.Collectors$$Lambda$5/391359742.accept(Unknown Source)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1359)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.guice.Main.main(Main.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
When is called the map.merge
BiConsumer<M, T> accumulator
= (map, element) -> map.merge(keyMapper.apply(element),
valueMapper.apply(element), mergeFunction);
It will do a null
check as first thing
if (value == null)
throw new NullPointerException();
I don't use Java 8 so often so i don't know if there are a better way to fix it, but fix it is a bit hard.
You could do:
Use filter to filter all NULL values, and in the Javascript code check if the server didn't send any answer for this id means that he didn't reply to it.
Something like this:
Map<Integer, Boolean> answerMap =
answerList
.stream()
.filter((a) -> a.getAnswer() != null)
.collect(Collectors.toMap(Answer::getId, Answer::getAnswer));
Or use peek, which is used to alter the stream element for element. Using peek you could change the answer to something more acceptable for map but it means edit your logic a bit.
Sounds like if you want to keep the current design you should avoid Collectors.toMap
Besides using an attribute to pass information from a servlet to a JSP page, one can also pass a parameter. That is done simply by redirecting to a URL that specifies the JSP page in question, and adding the normal parameter-passing-through-the-URL mechanism.
An example. The relevant part of the servlet code:
protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
response.setContentType( "text/html" );
// processing the request not shown...
//
// here we decide to send the value "bar" in parameter
// "foo" to the JSP page example.jsp:
response.sendRedirect( "example.jsp?foo=bar" );
}
And the relevant part of JSP page example.jsp
:
<%
String fooParameter = request.getParameter( "foo" );
if ( fooParameter == null )
{
%>
<p>No parameter foo given to this page.</p>
<%
}
else
{
%>
<p>The value of parameter foo is <%= fooParameter.toString() %>.</p>
<%
}
%>
I found that http://checkip.dyndns.org/ was giving me html tags I had to process but https://icanhazip.com/ was just giving me a simple string. Unfortunately https://icanhazip.com/ gives me the ip6 address and I needed ip4. Luckily there are 2 subdomains that you can choose from, ipv4.icanhazip.com and ipv6.icanhazip.com.
string externalip = new WebClient().DownloadString("https://ipv4.icanhazip.com/");
Console.WriteLine(externalip);
Console.WriteLine(externalip.TrimEnd());
Reference: Mastering Regular Expressions (Jeffrey E.F. Friedl) - O'Reilly
\b is equivalent to (?<!\w)(?=\w)|(?<=\w)(?!\w)
If you are allowed to use LINQ, take a look at the following example. It creates two DataTables with integer columns, fills them with some records, join them using LINQ query and outputs them to Console.
DataTable dt1 = new DataTable();
dt1.Columns.Add("CustID", typeof(int));
dt1.Columns.Add("ColX", typeof(int));
dt1.Columns.Add("ColY", typeof(int));
DataTable dt2 = new DataTable();
dt2.Columns.Add("CustID", typeof(int));
dt2.Columns.Add("ColZ", typeof(int));
for (int i = 1; i <= 5; i++)
{
DataRow row = dt1.NewRow();
row["CustID"] = i;
row["ColX"] = 10 + i;
row["ColY"] = 20 + i;
dt1.Rows.Add(row);
row = dt2.NewRow();
row["CustID"] = i;
row["ColZ"] = 30 + i;
dt2.Rows.Add(row);
}
var results = from table1 in dt1.AsEnumerable()
join table2 in dt2.AsEnumerable() on (int)table1["CustID"] equals (int)table2["CustID"]
select new
{
CustID = (int)table1["CustID"],
ColX = (int)table1["ColX"],
ColY = (int)table1["ColY"],
ColZ = (int)table2["ColZ"]
};
foreach (var item in results)
{
Console.WriteLine(String.Format("ID = {0}, ColX = {1}, ColY = {2}, ColZ = {3}", item.CustID, item.ColX, item.ColY, item.ColZ));
}
Console.ReadLine();
// Output:
// ID = 1, ColX = 11, ColY = 21, ColZ = 31
// ID = 2, ColX = 12, ColY = 22, ColZ = 32
// ID = 3, ColX = 13, ColY = 23, ColZ = 33
// ID = 4, ColX = 14, ColY = 24, ColZ = 34
// ID = 5, ColX = 15, ColY = 25, ColZ = 35
Have you tried
$(":first-child", element).toggleClass("redClass");
I think you want to set your element as a context for your search. There might be a better way to do this which some other jQuery guru will hop in here and throw out at you :)
It helps to group multiple statements into a single one so that a function-like macro can actually be used as a function. Suppose you have:
#define FOO(n) foo(n);bar(n)
and you do:
void foobar(int n) {
if (n)
FOO(n);
}
then this expands to:
void foobar(int n) {
if (n)
foo(n);bar(n);
}
Notice that the second call bar(n)
is not part of the if
statement anymore.
Wrap both into do { } while(0)
, and you can also use the macro in an if
statement.
You can try this code. This is Simple PHP Image Deleting code from the server.
<form method="post">
<input type="text" name="photoname"> // You can type your image name here...
<input type="submit" name="submit" value="Delete">
</form>
<?php
if (isset($_POST['submit']))
{
$photoname = $_POST['photoname'];
if (!unlink($photoname))
{
echo ("Error deleting $photoname");
}
else
{
echo ("Deleted $photoname");
}
}
?>
1) Use onbeforeunload, not onunload.
2) The important thing is to avoid executing a return statement. I don't mean, by this, to avoid returning from your handler. You return all right, but you do it by ensuring that you reach the end of the function and DO NOT execute a return statement. Under these conditions the built-in standard dialog does not occur.
3) You can, if you use onbeforeunload, run an ajax call in your unbeforeunload handler to tidy up on the server, but it must be a synchronous one, and you have to wait for and handle the reply in your onbeforeunload handler (still respecting condition (2) above). I do this and it works fine. If you do a synchronous ajax call, everything is held up until the response comes back. If you do an asynchronous one, thinking that you don't care about the reply from the server, the page unload continues and your ajax call is aborted by this process - including a remote script if it's running.
As I believe in the power of XML (for layouts), this is the equivalent for the accepted answer, but purely as an animation resource:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:interpolator/accelerate_decelerate"
android:fillAfter="true">
<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:duration="1000" />
<alpha
android:fromAlpha="1"
android:toAlpha="0"
android:duration="1000"
android:startOffset="1000"/>
</set>
The fillAfter
is for the fade to remain after completing the animation. The interpolator
handles interpolation of the animations, as you can guess. You can also use other types of interpolators, like Linear or Overshoot.
Be sure to start your animation on your view:
yourView.startAnimation(AnimationUtils.loadAnimation(co??ntext, R.anim.fade));
Hi! In order to use percentage(%), you must define the % of it parent element. If you use body{height: 100%} it will not work because it parent have no percentage in height. In that case in order to work that body height you must add this in html{height:100%}
In other case to get rid of that defining parent percentage you can use
body{height:100vh}
vh stands for viewport height
I think it help
This is the best and easy way to import font from google and
this is also a standard method to import font
Paste this code on your index page or on header
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
other method is to import on css like this:
@import url(http://fonts.googleapis.com/css?family=Oswald:400,300,700);
on your Css file as this code
body {
font-family: 'Oswald', sans-serif !important;
}
Note : The @import code line will be the first lines in your css file (style.css, etc.css). They can be used in any of the .css files and should always be the first line in these files. The following is an example:
Try below steps:
It worked for me.
This is not an answer, but it's hard to read if I put results in comment.
I get these results with a Mac Pro (Westmere 6-Cores Xeon 3.33 GHz). I compiled it with clang -O3 -msse4 -lstdc++ a.cpp -o a
(-O2 get same result).
uint64_t size=atol(argv[1])<<20;
unsigned 41950110000 0.811198 sec 12.9263 GB/s
uint64_t 41950110000 0.622884 sec 16.8342 GB/s
uint64_t size=1<<20;
unsigned 41950110000 0.623406 sec 16.8201 GB/s
uint64_t 41950110000 0.623685 sec 16.8126 GB/s
I also tried to:
for
statement in reverse: for (uint64_t i=size/8;i>0;i-=4)
. This gives the same result and proves the compile is smart enough to not divide size by 8 every iteration (as expected).Here is my wild guess:
The speed factor comes in three parts:
code cache: uint64_t
version has larger code size, but this does not have an effect on my Xeon CPU. This makes the 64-bit version slower.
Instructions used. Note not only the loop count, but the buffer is accessed with a 32-bit and 64-bit index on the two versions. Accessing a pointer with a 64-bit offset requests a dedicated 64-bit register and addressing, while you can use immediate for a 32-bit offset. This may make the 32-bit version faster.
Instructions are only emitted on the 64-bit compile (that is, prefetch). This makes 64-bit faster.
The three factors together match with the observed seemingly conflicting results.
I found a solution for how to set a global variable in a mailinglist posting via assign:
a <- "old"
test <- function () {
assign("a", "new", envir = .GlobalEnv)
}
test()
a # display the new value
"^.*$"
literally just means select everything
"^" // anchors to the beginning of the line
".*" // zero or more of any character
"$" // anchors to end of line
JDO is having advanced features than JPA see http://db.apache.org/jdo/jdo_v_jpa.html
I'm surprised no one mentioned the implicit style above. My preference is to use parens to wrap the string while lining the string lines up visually. Personally I think this looks cleaner and more compact than starting the beginning of the string on a tabbed new line.
Note that these parens are not part of a method call — they're only implicit string literal concatenation.
Python 2:
def fun():
print ('{0} Here is a really '
'long sentence with {1}').format(3, 5)
Python 3 (with parens for print function):
def fun():
print(('{0} Here is a really '
'long sentence with {1}').format(3, 5))
Personally I think it's cleanest to separate concatenating the long string literal from printing it:
def fun():
s = ('{0} Here is a really '
'long sentence with {1}').format(3, 5)
print(s)
I'm also surprised these aren't compile time constants. But I suppose you could create these values easily enough by simply executing an instruction that returns such an invalid result. Dividing by 0, log of 0, tan of 90, that kinda thing.
Solution for Eclipse Luna:
If I were you I'd just use a scanner and use ".nextByte()". You can cast that to a char and you're good.
this code will return duplicate value in same array
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
if(array_count_values($arr)[$item] > 1){
echo "Found Matched value : ".$item." <br />";
}
}
Try this code:
var string = 'AA.BB-CC-DD.zip';
array = string.split(/[,.]/);
Here's an example of the string "abc" repeated
3 times:
#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <iterator>
using namespace std;
int main() {
ostringstream repeated;
fill_n(ostream_iterator<string>(repeated), 3, string("abc"));
cout << "repeated: " << repeated.str() << endl; // repeated: abcabcabc
return 0;
}
Sub Addrisk()
Dim rActive As Range
Dim Count_Id_Column as long
Set rActive = ActiveCell
Application.ScreenUpdating = False
with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
for i = 1 to .range("A1045783").end(xlup).row
if 'something' = 'something' then
.range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
.range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
.range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
'change I to move on to next row (will get + 1 end of iteration)
i = i + 1
end if
On Error Resume Next
.SpecialCells(xlCellTypeConstants).ClearContents
On Error GoTo 0
End With
next i
End With
Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates
End Sub
Use DateTime.ToString
with the specified format MM.dd.yyyy
:
this.TextBox3.Text = DateTime.Now.ToString("MM.dd.yyyy");
Here, MM
means the month from 01 to 12, dd
means the day from 01 to 31 and yyyy
means the year as a four-digit number.
So, because everyone is posting their solution and none was good for me, here is mine (tested on Chrome & Firefox).
table { height: 1px; } /* Will be ignored, don't worry. */
tr { height: 100%; }
td { height: 100%; }
td > div { height: 100%; }
Fiddle: https://jsfiddle.net/nh6g5fzv/
--
Edit: one thing you might want to note, if you want to apply a padding to the div in the td, you must add box-sizing: border-box;
because of height: 100%
.
CLI has some limit when ouput is displayed. I suggest to export output into local file:
$hive -e 'show partitions table;' > partitions
This happened to me when I forgot a , in the arguments for a locally defined macro. Spent hours trying to figure it out (barely acquainted with autotools)...
AC_CHECK_MACRO([Foo]
AC_LOCAL_DO([......
should have been
AC_CHECK_MACRO([Foo], # <-- Notice comma, doh!
AC_LOCAL_DO([......
Seems like it should have given me an error or such, but I suppose being a macro processor it can only do what its told.
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
If the users enter an incorrect value, apply a 1px red color border to the input field:
document.getElementById('fName').style.border ="1px solid red";
If the user enters a correct value, remove the border from the input field:
document.getElementById('fName').style.border ="";
you can use the command reset
git reset --soft HEAD^1
then:
git reset <files>
git commit --amend
and
git push -f
When you say
val map = scala.collection.mutable.Map
you are not creating a map instance, but instead aliasing the Map type.
map: collection.mutable.Map.type = scala.collection.mutable.Map$@fae93e
Try instead the following:
scala> val map = scala.collection.mutable.Map[String, Int]()
map: scala.collection.mutable.Map[String,Int] = Map()
scala> map("asdf") = 9
scala> map
res6: scala.collection.mutable.Map[String,Int] = Map((asdf,9))
If your button is loading from an AJAX call, you should use
$(document).on("click", ".delegate_update_success", function(){
location.reload(true);
});
instead of
$( ".delegate_update_success" ).click(function() {
location.reload();
});
Also note the true
parameter for the location.reload
function.
Are the classes imported? Try pressing CTRL
+ SHIFT
+ O
to resolve the imports. If this does not work you need to include the application servers runtime libraries.
Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337
You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties
Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0
only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden
, you can eliminate this problem:
div {_x000D_
width:100px;_x000D_
height:20px;_x000D_
}_x000D_
.menu {_x000D_
visibility:hidden;_x000D_
opacity:0;_x000D_
transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
_x000D_
background:#eee;_x000D_
width:100px;_x000D_
margin:0;_x000D_
padding:5px;_x000D_
list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
visibility:visible;_x000D_
opacity:1;_x000D_
}
_x000D_
<div>_x000D_
<a href="#">Open Menu</a>_x000D_
<ul class="menu">_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
Basically it means "nothing" or "no type"
There are 3 basic ways that void is used:
Function argument: int myFunc(void)
-- the function takes nothing.
Function return value: void myFunc(int)
-- the function returns nothing
Generic data pointer: void* data
-- 'data' is a pointer to data of unknown type, and cannot be dereferenced
Note: the void
in a function argument is optional in C++, so int myFunc()
is exactly the same as int myFunc(void)
, and it is left out completely in C#. It is always required for a return value.
The simple naive way that is slow because it opens and positions the file pointer to End-Of-File multiple times.
@echo off
command1 >output.txt
command2 >>output.txt
...
commandN >>output.txt
A better way - easier to write, and faster because the file is opened and positioned only once.
@echo off
>output.txt (
command1
command2
...
commandN
)
Another good and fast way that only opens and positions the file once
@echo off
call :sub >output.txt
exit /b
:sub
command1
command2
...
commandN
Edit 2020-04-17
Every now and then you may want to repeatedly write to two or more files. You might also want different messages on the screen. It is still possible to to do this efficiently by redirecting to undefined handles outside a parenthesized block or subroutine, and then use the &
notation to reference the already opened files.
call :sub 9>File1.txt 8>File2.txt
exit /b
:sub
echo Screen message 1
>&9 File 1 message 1
>&8 File 2 message 1
echo Screen message 2
>&9 File 1 message 2
>&8 File 2 message 2
exit /b
I chose to use handles 9 and 8 in reverse order because that way is more likely to avoid potential permanent redirection due to a Microsoft redirection implementation design flaw when performing multiple redirections on the same command. It is highly unlikely, but even that approach could expose the bug if you try hard enough. If you stage the redirection than you are guaranteed to avoid the problem.
3>File1.txt ( 4>File2.txt call :sub)
exit /b
:sub
etc.
The way that Android detects emulators is by scanning ports starting at port 5555.
The number you see in the adb devices
list (in your case 5554) will be one less than the port that adb is finding open.
You probably have a process running that is listening on port 5555. To get rid of the "offline" device, you will need to find that application and close it or reconfigure it to listen to a different port.
Try this it will work fine.
<script>
function echoHello(){
alert("<?PHP hello(); ?>");
}
</script>
<?PHP
FUNCTION hello(){
echo "Call php function on onclick event.";
}
?>
<button onclick="echoHello()">Say Hello</button>
For example, to set the background to your favorite/Branding color
Add Below Meta property to your HTML code in HEAD Section
<head>
...
<meta name="theme-color" content="Your Hexadecimal Code">
...
</head>
Example
<head>
...
<meta name="theme-color" content="#444444">
...
</head>
In Below Image, I just mentioned How Chrome taken your theme-color Property
Firefox OS, Safari, Internet Explorer and Opera Coast allow you to define colors for elements of the browser, and even the platform using meta tags.
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
From the guidelinesDocuments Here
Hiding Safari User Interface Components
Set the apple-mobile-web-app-capable meta tag to yes to turn on standalone mode. For example, the following HTML displays web content using standalone mode.
<meta name="apple-mobile-web-app-capable" content="yes">
Changing the Status Bar Appearance
You can change the appearance of the default status bar to either black or black-translucent. With black-translucent, the status bar floats on top of the full screen content, rather than pushing it down. This gives the layout more height, but obstructs the top. Here’s the code required:
<meta name="apple-mobile-web-app-status-bar-style" content="black">
For more on status bar appearance, see apple-mobile-web-app-status-bar-style.
For Example:
Screenshot using black-translucent
Screenshot using black
Yes, I would use explode or you could use:
preg_split
Which is the advised method with PHP 6. preg_split Documentation
I have a Mac and I clicked Code > Preferences > Settings > Workspace > Formatting and then selected Format On Save.
Now every time I hit cmd + s it auto formats the file.
This is something you solve in the "controller", which is the point of logicless templating.
// some function that retreived data through ajax
function( view ){
if ( !view.avatar ) {
// DEFAULTS can be a global settings object you define elsewhere
// so that you don't have to maintain these values all over the place
// in your code.
view.avatar = DEFAULTS.AVATAR;
}
// do template stuff here
}
This is actually a LOT better then maintaining image url's or other media that might or might not change in your templates, but takes some getting used to. The point is to unlearn template tunnel vision, an avatar img url is bound to be used in other templates, are you going to maintain that url on X templates or a single DEFAULTS settings object? ;)
Another option is to do the following:
// augment view
view.hasAvatar = !!view.avatar;
view.noAvatar = !view.avatar;
And in the template:
{{#hasAvatar}}
SHOW AVATAR
{{/hasAvatar}}
{{#noAvatar}}
SHOW DEFAULT
{{/noAvatar}}
But that's going against the whole meaning of logicless templating. If that's what you want to do, you want logical templating and you should not use Mustache, though do give it yourself a fair chance of learning this concept ;)
I think this solve the problem :
boolean allOk = false;
try{
q();
allOk = true;
} finally {
try {
is.close();
} catch (Exception e) {
if(allOk) {
throw new SomeException(e);
}
}
}
After creating Set just convert it to List and get by index from List:
Set<String> stringsSet = new HashSet<>();
stringsSet.add("string1");
stringsSet.add("string2");
List<String> stringsList = new ArrayList<>(stringsSet);
stringsList.get(0); // "string1";
stringsList.get(1); // "string2";
Highlight your block with: ShiftV
Comment the selected block out with: :norm i#
(lower case i)
To uncomment, highlight your block again, and uncomment with: :norm ^x
The :norm
command performs an action for every selected line. Commenting will insert a #
at the start of every line, and uncommenting will delete that #
.
__init__
would be treated as Constructor where as __call__
methods can be called with objects any number of times. Both __init__
and __call__
functions do take default arguments.
If you have a TRY/CATCH block then the likely cause is that you are catching a transaction abort exception and continue. In the CATCH block you must always check the XACT_STATE()
and handle appropriate aborted and uncommitable (doomed) transactions. If your caller starts a transaction and the calee hits, say, a deadlock (which aborted the transaction), how is the callee going to communicate to the caller that the transaction was aborted and it should not continue with 'business as usual'? The only feasible way is to re-raise an exception, forcing the caller to handle the situation. If you silently swallow an aborted transaction and the caller continues assuming is still in the original transaction, only mayhem can ensure (and the error you get is the way the engine tries to protect itself).
I recommend you go over Exception handling and nested transactions which shows a pattern that can be used with nested transactions and exceptions:
create procedure [usp_my_procedure_name]
as
begin
set nocount on;
declare @trancount int;
set @trancount = @@trancount;
begin try
if @trancount = 0
begin transaction
else
save transaction usp_my_procedure_name;
-- Do the actual work here
lbexit:
if @trancount = 0
commit;
end try
begin catch
declare @error int, @message varchar(4000), @xstate int;
select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
if @xstate = -1
rollback;
if @xstate = 1 and @trancount = 0
rollback
if @xstate = 1 and @trancount > 0
rollback transaction usp_my_procedure_name;
raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
end catch
end
go
Unicode is an agreed-upon format for the binary representation of characters and various kinds of formatting (e.g. lower case/upper case, new line, carriage return), and other "things" (e.g. emojis). A computer is no less capable of storing a unicode representation (a series of bits), whether in memory or in a file, than it is of storing an ascii representation (a different series of bits), or any other representation (series of bits).
For communication to take place, the parties to the communication must agree on what representation will be used.
Because unicode seeks to represent all the possible characters (and other "things") used in inter-human and inter-computer communication, it requires a greater number of bits for the representation of many characters (or things) than other systems of representation that seek to represent a more limited set of characters/things. To "simplify," and perhaps to accommodate historical usage, unicode representation is almost exclusively converted to some other system of representation (e.g. ascii) for the purpose of storing characters in files.
It is not the case that unicode cannot be used for storing characters in files, or transmitting them through any communications channel, simply that it is not.
The term "string," is not precisely defined. "String," in its common usage, refers to a set of characters/things. In a computer, those characters may be stored in any one of many different bit-by-bit representations. A "byte string" is a set of characters stored using a representation that uses eight bits (eight bits being referred to as a byte). Since, these days, computers use the unicode system (characters represented by a variable number of bytes) to store characters in memory, and byte strings (characters represented by single bytes) to store characters to files, a conversion must be used before characters represented in memory will be moved into storage in files.
Using the Apache Commons IO library...
boolean isFileUnlocked = false;
try {
org.apache.commons.io.FileUtils.touch(yourFile);
isFileUnlocked = true;
} catch (IOException e) {
isFileUnlocked = false;
}
if(isFileUnlocked){
// Do stuff you need to do with a file that is NOT locked.
} else {
// Do stuff you need to do with a file that IS locked
}
public static final void generateRange(final Date dateFrom, final Date dateTo)
{
final Calendar current = Calendar.getInstance();
current.setTime(dateFrom);
while (!current.getTime().after(dateTo))
{
// TODO
current.add(Calendar.DATE, 1);
}
}