I don't know about the older versions but for SSMS 2016 you can go to the Object Explorer and right click on the Databases entry. Then select Attach... in the context menu. Here you can browse to the .mdf file and open it.
To perform this operation see the next images:
and next step is add *.mdf file,
very important, the .mdf file must be located in C:......\MSSQL12.SQLEXPRESS\MSSQL\DATA
Now remove the log file
Just to make this absolutely clear for all:
A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.
This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.
To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.
To qualify the preferred naming conventions:
You can use angular-recursion-injector for that: https://github.com/knyga/angular-recursion-injector
Allows you to do unlimited depth nesting with conditioning. Does recompilation only if needed and compiles only right elements. No magic in code.
<div class="node">
<span>{{name}}</span>
<node--recursion recursion-if="subNode" ng-model="subNode"></node--recursion>
</div>
One of the things that allows it to work faster and simpler then the other solutions is "--recursion" suffix.
I ran into a similar situation. I did have access to a larger data drive. Depending on your situation, and the access you have to the server you can consider
ln -s /datavol/path/to/your/.conda /home/user/.conda
Then subsequent conda commands will put data to the symlinked dir in datavol
It's simple. Just do this:
#include <iostream>
#include <vector>
#include <string.h>
int main(int argc, char *argv[])
{
std::vector<std::string> argList;
for(int i=0;i<argc;i++)
argList.push_back(argv[i]);
//now you can access argList[n]
}
@Benjamin Lindley You are right. This is not a good solution. Please read the one answered by juanchopanza.
There's a function empty()
ready for you in std::string:
std::string a;
if(a.empty())
{
//do stuff. You will enter this block if the string is declared like this
}
or
std::string a;
if(!a.empty())
{
//You will not enter this block now
}
a = "42";
if(!a.empty())
{
//And now you will enter this block.
}
Use asp:image
<asp:Image id="Image1" runat="server"
AlternateText="Image text"
ImageAlign="left"
ImageUrl="images/image1.jpg"/>
and codebehind to change image url
Image1.ImageUrl = "/MyProject;component/Images/down.png";
I've seen people mention a rename
command, but it is not routinely available on Unix systems (as opposed to Linux systems, say, or Cygwin - on both of which, rename is an executable rather than a script). That version of rename
has a fairly limited functionality:
rename from to file ...
It replaces the from part of the file names with the to, and the example given in the man page is:
rename foo foo0 foo? foo??
This renames foo1 to foo01, and foo10 to foo010, etc.
I use a Perl script called rename
, which I originally dug out from the first edition Camel book, circa 1992, and then extended, to rename files.
#!/bin/perl -w
#
# @(#)$Id: rename.pl,v 1.7 2008/02/16 07:53:08 jleffler Exp $
#
# Rename files using a Perl substitute or transliterate command
use strict;
use Getopt::Std;
my(%opts);
my($usage) = "Usage: $0 [-fnxV] perlexpr [filenames]\n";
my($force) = 0;
my($noexc) = 0;
my($trace) = 0;
die $usage unless getopts('fnxV', \%opts);
if ($opts{V})
{
printf "%s\n", q'RENAME Version $Revision: 1.7 $ ($Date: 2008/02/16 07:53:08 $)';
exit 0;
}
$force = 1 if ($opts{f});
$noexc = 1 if ($opts{n});
$trace = 1 if ($opts{x});
my($op) = shift;
die $usage unless defined $op;
if (!@ARGV) {
@ARGV = <STDIN>;
chop(@ARGV);
}
for (@ARGV)
{
if (-e $_ || -l $_)
{
my($was) = $_;
eval $op;
die $@ if $@;
next if ($was eq $_);
if ($force == 0 && -f $_)
{
print STDERR "rename failed: $was - $_ exists\n";
}
else
{
print "+ $was --> $_\n" if $trace;
print STDERR "rename failed: $was - $!\n"
unless ($noexc || rename($was, $_));
}
}
else
{
print STDERR "$_ - $!\n";
}
}
This allows you to write any Perl substitute or transliterate command to map file names. In the specific example requested, you'd use:
rename 's/^/new./' original.filename
I use them sparingly, but they can be pretty convenient:
def log(msg):
log.logfile.write(msg)
Now I can use log
throughout my module, and redirect output simply by setting log.logfile
. There are lots and lots of other ways to accomplish that, but this one's lightweight and dirt simple. And while it smelled funny the first time I did it, I've come to believe that it smells better than having a global logfile
variable.
You should have if row[2] != "0"
. Otherwise it's not checking to see if the string value is equal to 0.
Okay, redis is pretty user friendly but there are some gotchas.
Here are just some easy commands for working with redis on Ubuntu:
install:
sudo apt-get install redis-server
start with conf:
sudo redis-server <path to conf>
sudo redis-server config/redis.conf
stop with conf:
redis-ctl shutdown
(not sure how this shuts down the pid specified in the conf. Redis must save the path to the pid somewhere on boot)
log:
tail -f /var/log/redis/redis-server.log
Also, various example confs floating around online and on this site were beyond useless. The best, sure fire way to get a compatible conf is to copy-paste the one your installation is already using. You should be able to find it here:
/etc/redis/redis.conf
Then paste it at <path to conf>
, tweak as needed and you're good to go.
Owen has a good answer. If you want just the key, and you are working with an array this might also be useful.
foreach(array_keys($array) as $key) {
// do stuff
}
Send email with attachment using PowerShell -
$EmailTo = "[email protected]" // [email protected]
$EmailFrom = "[email protected]" // [email protected]
$Subject = "zx" //subject
$Body = "Test Body" // Body of message
$SMTPServer = "smtp.gmail.com"
$filenameAndPath = "G:\abc.jpg" // Attachment
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("[email protected]", "xxxxxxxx"); // xxxxxx-password
$SMTPClient.Send($SMTPMessage)
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand.
When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.
If the first operand returns a value of true then the second operand is evaluated. If the second operand returns a value of true then && operator is then applied to the first and second operands.
Similar for | and ||.
Please note, I wrote this answer based on Python 3.x
. No worries you can assign print()
statement to the variable like this.
>>> var = print('some text')
some text
>>> var
>>> type(var)
<class 'NoneType'>
According to the documentation,
All non-keyword arguments are converted to strings like
str()
does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also beNone
, which means to use the default values. If no objects are given, print() will just write end.The file argument must be an object with a
write(string)
method; if it is not present orNone
,sys.stdout
will be used. Since printed arguments are converted to text strings,print()
cannot be used with binary mode file objects. For these, usefile.write(...)
instead.
That's why we cannot assign print()
statement values to the variable. In this question you have ask (or any function)
. So print()
also a function with the return value with None
. So the return value of python function is None
. But you can call the function(with parenthesis ()) and save the return value in this way.
>>> var = some_function()
So the var
variable has the return value of some_function()
or the default value None
. According to the documentation about print()
, All non-keyword arguments are converted to strings like str() does and written to the stream
. Lets look what happen inside the str()
.
Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of
str()
depends on whether encoding or errors is given, as follows.
So we get a string object, then you can modify the below code line as follows,
>>> var = str(some_function())
or you can use str.join()
if you really have a string
object.
Return a string which is the concatenation of the strings in iterable. A
TypeError
will be raised if there are any non-string values in iterable, includingbytes
objects. The separator between elements is the string providing this method.
change can be as follows,
>>> var = ''.join(some_function()) # you can use this if some_function() really returns a string value
try this code
DataRow foundRow = FinalDt.Rows.Find(Value);
but set at lease one primary key
I've been really tired of the enormous amount of JavaScript templating engines out there, and all their inline HTML-templates, different markup styles, etc., and decided to build a small library that enables XSLT formatting for JSON data structures. Not rocket science in any way -- it's just JSON parsed to XML and then formatted with a XSLT document. It's fast too, not as fast as JavaScript template engines in Chrome, but in most other browsers it's at least as fast as the JS engine alternative for larger data structures.
I got the same error: SyntaxError: can't assign to literal when I was trying to assign multiple variables in a single line.
I was assigning the values as shown below:
score = 0, isDuplicate = None
When I shifted them to another line, it got resolved:
score = 0
isDuplicate = None
I don't know why python does not allow multiple assignments at the same line but that's how it is done.
There is one more way to asisgn it in single line ie. Separate them with a semicolon in place of comma. Check the code below:
score = 0 ; duplicate = None
The best solution I have found (to an otherwise frustrating problem that should have been solved in the framework) is similar to vaychick's.
Just set number of lines to 0 in either IB or code
myLabel.numberOfLines = 0;
This will display the lines needed but will reposition the label so its centered horizontally (so that a 1 line and 3 line label are aligned in their horizontal position). To fix that add:
CGRect currentFrame = myLabel.frame;
CGSize max = CGSizeMake(myLabel.frame.size.width, 500);
CGSize expected = [myString sizeWithFont:myLabel.font constrainedToSize:max lineBreakMode:myLabel.lineBreakMode];
currentFrame.size.height = expected.height;
myLabel.frame = currentFrame;
I got the same issue, and it was happening because of different feature module included this component by mistake. When removed it from the other feature, it worked!
var now = System.DateTime.Now;
var result = now.AddDays(-((now.DayOfWeek - System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7)).Date;
CSS has many pseudo selector like, :active, :hover, :focus, so you can use.
Html
<div class="col-sm-12" id="my_styles">
<button type="submit" class="btn btn-warning" id="1">Button1</button>
<button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>
css
.btn{
background: #ccc;
} .btn:focus{
background: red;
}
Here's a flow chart that illustrates a for loop:
The equivalent C code would be
for(i = 2; i <= 6; i = i + 2) {
printf("%d\t", i + 1);
}
I found this and several other examples on one of Tenouk's C Laboratory practice worksheets.
You ca use -a
git commit -h
...
Commit contents options
-a, -all commit all changed files
...
git commit -a # It will add all files and also will open your default text editor.
Yes, your compiler is expecting void *. Just cast them to void *.
/* for instance... */
printf("The value of s is: %p\n", (void *) s);
printf("The direction of s is: %p\n", (void *) &s);
You can use input text with "list" attribute, which refers to the datalist of values.
<input type="text" name="city" list="cityname">_x000D_
<datalist id="cityname">_x000D_
<option value="Boston">_x000D_
<option value="Cambridge">_x000D_
</datalist>
_x000D_
This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist
See:- ConnectionStrings content on this subject. There is no default command timeout property.
I just went into the manifest and changed android:label="...." to the name of the application. Once Id changed this, the title and the actual app name changed to that :)
I ran into an article that illustrates a method where the data from the same excel sheet can be imported in the selected table until there is no modifications in excel with data types.
If the data is inserted or overwritten with new ones, importing process will be successfully accomplished, and the data will be added to the table in SQL database.
The article may be found here: http://www.sqlshack.com/using-ssis-packages-import-ms-excel-data-database/
Hope it helps.
As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &
. That also requires using parentheses so that &
wouldn't take precedence.
It would go something like this:
mask = ((50 < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...
In order to avoid that, you can build series for lower and upper limits:
low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)
Now you can slice it as follows:
mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out:
dyastolic blood pressure heart rate pulse oximetry respiratory rate \
17 136 62 97 15
69 110 85 96 18
72 105 85 97 16
161 126 57 99 16
286 127 84 99 12
435 92 67 96 13
499 110 66 97 15
systolic blood pressure temperature
17 141 37
69 155 38
72 154 36
161 153 36
286 156 37
435 155 36
499 149 36
And for assignment you can use np.where:
df['class'] = np.where(mask, 'excellent', 'critical')
concatenated_list = list_1 + list_2
First, create staticfiles folder. Inside that folder create css, js, and img folder.
settings.py
import os
PROJECT_DIR = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, 'staticfiles'),
)
main urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings
admin.autodiscover()
urlpatterns = patterns('',
.......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
template
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
The .bashrc file is in your home directory.
So from command line do:
cd
ls -a
This will show all the hidden files in your home directory. "cd" will get you home and ls -a will "list all".
In general when you see ~/ the tilda slash refers to your home directory. So ~/.bashrc is your home directory with the .bashrc file.
And the standard path to homebrew is in /usr/local/ so if you:
cd /usr/local
ls | grep -i homebrew
you should see the homebrew directory (/usr/local/homebrew). Source
Yes sometimes you may have to create this file and the typical format of a .bashrc file is:
# .bashrc
# User specific aliases and functions
. .alias
alias ducks='du -cks * | sort -rn | head -15'
# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
PATH=$PATH:/home/username/bin:/usr/local/homebrew
export PATH
If you create your own .bashrc file make sure that the following line is in your ~/.bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
IDE: The MS Office of Programming. It's where you type your code, plus some added features to make you a happier programmer. (e.g. Eclipse, Netbeans). Car body: It's what you really touch, see and work on.
Library: A library is a collection of functions, often grouped into multiple program files, but packaged into a single archive file. This contains programs created by other folks, so that you don't have to reinvent the wheel. (e.g. junit.jar, log4j.jar). A library generally has a key role, but does all of its work behind the scenes, it doesn't have a GUI. Car's engine.
API: The library publisher's documentation. This is how you should use my library. (e.g. log4j API, junit API). Car's user manual - yes, cars do come with one too!
What is a kit? It's a collection of many related items that work together to provide a specific service. When someone says medicine kit, you get everything you need for an emergency: plasters, aspirin, gauze and antiseptic, etc.
SDK: McDonald's Happy Meal. You have everything you need (and don't need) boxed neatly: main course, drink, dessert and a bonus toy. An SDK is a bunch of different software components assembled into a package, such that they're "ready-for-action" right out of the box. It often includes multiple libraries and can, but may not necessarily include plugins, API documentation, even an IDE itself. (e.g. iOS Development Kit).
Toolkit: GUI. GUI. GUI. When you hear 'toolkit' in a programming context, it will often refer to a set of libraries intended for GUI development. Since toolkits are UI-centric, they often come with plugins (or standalone IDE's) that provide screen-painting utilities. (e.g. GWT)
Framework: While not the prevalent notion, a framework can be viewed as a kit. It also has a library (or a collection of libraries that work together) that provides a specific coding structure & pattern (thus the word, framework). (e.g. Spring Framework)
I needed to rotate an object but have a call back function. Inspired by John Kern's answer I created this.
function animateRotate (object,fromDeg,toDeg,duration,callback){
var dummy = $('<span style="margin-left:'+fromDeg+'px;">')
$(dummy).animate({
"margin-left":toDeg+"px"
},
{
duration:duration,
step: function(now,fx){
$(object).css('transform','rotate(' + now + 'deg)');
if(now == toDeg){
if(typeof callback == "function"){
callback();
}
}
}
}
)};
Doing this you can simply call the rotate on the object like so... (in my case I'm doing it on a disclosure triangle icon that has already been rotated by default to 270 degress and I'm rotating it another 90 degrees to 360 degrees at 1000 milliseconds. The final argument is the callback after the animation has finished.
animateRotate($(".disclosure_icon"),270,360,1000,function(){
alert('finished rotate');
});
Please Look at the following:
Here is what's working:
1.) top menu buttons are visible and highlight correctly
2.) sub menu buttons are not visible until top menu is clicked
Here is what needs work:
1.) when sub menu is clicked, looking for new page to keep the selected sub menu open (i will highlight the selected sub menu button for further clarification on navigation)
Please see code here: http://jsbin.com/ePawaju/1/edit
or here: http://www.ceramictilepro.com/_6testingonly.php#
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
Do I need to put this script in the head section? Where is the best place?
<div class="left">
<nav class="vmenu">
<ul class="vnavmenu">
<li data-ref="Top1"><a class="hiLite navBarButton2" href="#">Home</a>
</li>
</ul>
<ul class="Top1 navBarTextSize">
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub1</a>
</li>
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub2</a>
</li>
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub3</a>
</li>
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub4</a>
</li>
</ul>
<ul class="vnavmenu">
<li data-ref="Top2"><a class="hiLite navBarButton2" href="#">Repairs</a>
</li>
</ul>
<ul class="Top2 navBarTextSize">
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">1sub1</a>
</li>
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">2sub2</a>
</li>
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">3sub3</a>
</li>
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">4sub4</a>
</li>
</ul>
</nav>
JQuery is new to me, any help would greatly be appreciated :) var submenu;
$('.vnavmenu li').click(function () {
var elems = $('.vmenu ul:not(.vnavmenu)').length;
var $refClass = $('.' + $(this).attr('data-ref'));
var visible = $refClass.is(':visible');
$('.vmenu ul:not(.vnavmenu)').slideUp(100, function () {
if (elems == 1) {
if (!visible) $refClass.slideDown('fast');
}
elems--;
});
if (visible) $('#breadcrumbs-pc').animate({
'margin-top': '0rem'
}, 100);
else $('#breadcrumbs-pc').animate({
'margin-top': '5rem'
}, 100);
});
As has been pointed out ... in a select
box, the .val()
attribute will give you the value of the selected option. If the selected option does not have a value attribute it will default to the display value of the option (which is what the examples on the jQuery documentation of .val
show.
you want to use .text()
of the selected option:
$('#Crd option:selected').text()
It is not easier to replace all new lines by +
, add a 0
and send it to the Ruby
interpreter?
(sed -e "s/$/+/" file; echo 0)|irb
If you do not have irb
, you can send it to bc
, but you have to remove all newlines except the last one (of echo
). It is better to use tr
for this, unless you have a PhD in sed
.
(sed -e "s/$/+/" file|tr -d "\n"; echo 0)|bc
Error checking and handling is the programmer's friend. Check the return values of the initializing and executing cURL functions. curl_error()
and curl_errno()
will contain further information in case of failure:
try {
$ch = curl_init();
// Check if initialization had gone wrong*
if ($ch === false) {
throw new Exception('failed to initialize');
}
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(/* ... */);
$content = curl_exec($ch);
// Check the return value of curl_exec(), too
if ($content === false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
/* Process $content here */
// Close curl handle
curl_close($ch);
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
* The curl_init()
manual states:
Returns a cURL handle on success, FALSE on errors.
I've observed the function to return FALSE
when you're using its $url
parameter and the domain could not be resolved. If the parameter is unused, the function might never return FALSE
. Always check it anyways, though, since the manual doesn't clearly state what "errors" actually are.
abs()
:
Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float.
Also it works on complex variable also i.e. abs(a+bj)
also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)
math.fabs()
:
It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).
#include<stdio.h>
int main()
{
int a,b,i,c,j;
printf("\n Enter the two no. in between you want to check:");
scanf("%d%d",&a,&c);
printf("%d-%d\n",a,c);
for(j=a;j<=c;j++)
{
b=0;
for(i=1;i<=c;i++)
{
if(j%i==0)
{
b++;
}
}
if(b==2)
{
printf("\nPrime number:%d\n",j);
}
else
{
printf("\n\tNot prime:%d\n",j);
}
}
}
Try this:
<div class="row">
<div class="alert alert-info" style="min-height:100px;">
<div class="col-xs-9">
<a href="#" class="alert-link">Summary:Its some
description.......testtesttest</a>
</div>
<div class="col-xs-3">
<button type="button" class="btn btn-primary btn-lg">Large button</button>
</div>
</div>
</div>
Demo:
This is my personal solution for an i element inside a div
<div class="circle">
<i class="fa fa-plus icon">
</i></div>
.circle {
border-radius: 50%;
color: blue;
background-color: red;
height:100px;
width:100px;
text-align: center;
line-height: 100px;
}
.icon {
font-size: 50px;
vertical-align: middle;
}
Using a dict to grab headings then looping through gets you what you need cleanly.
import csv
ct = 0
cols_i_want = {'cost' : -1, 'date' : -1}
with open("file1.csv","rb") as source:
rdr = csv.reader( source )
with open("result","wb") as result:
wtr = csv.writer( result )
for row in rdr:
if ct == 0:
cc = 0
for col in row:
for ciw in cols_i_want:
if col == ciw:
cols_i_want[ciw] = cc
cc += 1
wtr.writerow( (row[cols_i_want['cost']], row[cols_i_want['date']]) )
ct += 1
If you are using JSP 2.0 and above It will come with the EL support:
so that you can write in plain english and use and
with empty
operators to write your test:
<c:if test="${(empty object_1.attribute_A) and (empty object_2.attribute_B)}">
This one worked for me
var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]});
you can also use "global"
Example:
declare like this :
app.use(function(req,res,next){
global.site_url = req.headers.host; // hostname = 'localhost:8080'
next();
});
Use like this: in any views or ejs file <% console.log(site_url); %>
in js files console.log(site_url);
If it's an NSMutableString (which I would recommend since you're changing it dynamically), you can use:
[myString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];
Here you go:
public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
return encoding.GetBytes(str);
}
public static String ToBinary(Byte[] data)
{
return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}
// Use any sort of encoding you like.
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));
PEP 8 advises the first form for readability. You can find it here.
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Android Documentation on Manifest.permission.Manifest.permission.WRITE_EXTERNAL_STORAGE states:
Starting in API level 19, this permission is not required to read/write files in your application-specific directories returned by getExternalFilesDir(String) and getExternalCacheDir().
I think that this means you do not have to code for the run-time implementation of the WRITE_EXTERNAL_STORAGE permission unless the app is writing to a directory that is not specific to your app.
You can define the max sdk version in the manifest per permission like:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="19" />
Also make sure to change the target SDK in the build.graddle and not the manifest, the gradle settings will always overwrite the manifest settings.
android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
minSdkVersion 17
targetSdkVersion 22
}
I think the problem is in your JOIN
condition.
SELECT user.user_fname,
user.user_lname,
parent.user_fname,
parent.user_lname
FROM users AS user
JOIN users AS parent
ON parent.user_id = user.user_parent_id
WHERE user.user_id = $_GET[id]
Edit:
You should probably use LEFT JOIN
if there are users with no parents.
For en-US ( American English ) strings this should suffice:
"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation".replace( /[^a-zA-Z ]/g, '').replace( /\s\s+/g, ' ' )
Be aware that if you support UTF-8 and characters like chinese/russian and all, this will replace them as well, so you really have to specify what you want.
I just came across this error and it was because I was trying to write the build file to a network drive that was not working. Tried again from my desktop and it worked just fine. (You may have to "Clean" the build after you move it. Just choose "Clean all Targets" from the "Build" drop-down menu).
Tobias is correct though, dig into the details on the code by right-clicking it to see what your specific problem is.
Here's some that I needed to include the date-time stamp in the folder name for dumping files from a web scraper.
# import time and OS modules to use to build file folder name
import time
import os
# Build string for directory to hold files
# Output Configuration
# drive_letter = Output device location (hard drive)
# folder_name = directory (folder) to receive and store PDF files
drive_letter = r'D:\\'
folder_name = r'downloaded-files'
folder_time = datetime.now().strftime("%Y-%m-%d_%I-%M-%S_%p")
folder_to_save_files = drive_letter + folder_name + folder_time
# IF no such folder exists, create one automatically
if not os.path.exists(folder_to_save_files):
os.mkdir(folder_to_save_files)
From Chrome 68:
"Show timestamps" moved to settings
The Show timestamps checkbox previously in Console Settings Console Settings has moved to Settings.
This link will help you in understanding pass by reference in C#. Basically,when an object of reference type is passed by value to an method, only methods which are available on that object can modify the contents of object.
For example List.sort() method changes List contents but if you assign some other object to same variable, that assignment is local to that method. That is why myList remains unchanged.
If we pass object of reference type by using ref keyword then we can assign some other object to same variable and that changes entire object itself.
(Edit: this is the updated version of the documentation linked above.)
I was able to override compatibility mode by specifying the meta tag as THE FIRST TAG in the head section, not just the first meta tag but as and only as the VERY FIRST TAG.
Thanks to @stefan.s for putting me on to it in your excellent answer. Prior to reading that I had:
THIS DID NOT WORK
<head>
<link rel="stylesheet" type="text/css" href="/qmuat/plugins/editors/jckeditor/typography/typography.php"/>
<meta http-equiv="x-ua-compatible" content="IE=9" >
moved the link tag out of the way and it worked
THIS WORKS:
<head><meta http-equiv="x-ua-compatible" content="IE=9" >
So an IE8 client set to use compatibility renders the page as IE8 Standard mode - the content='IE=9' means use the highest standard available up to and including IE9.
This is not a elegant method, is a very 'low level' implementation of a simple state machine (bitfield state machine), possibly the most anti pythonic mode to resolve this, however re module also implements a too complex state machine to resolve this simple task, so i think this is a good solution.
def splitSymbol(s):
si, ci, state = 0, 0, 0 # start_index, current_index
'''
state bits:
0: no yields
1: lower yields
2: lower yields - 1
4: upper yields
8: digit yields
16: other yields
32 : upper sequence mark
'''
for c in s:
if c.islower():
if state & 1:
yield s[si:ci]
si = ci
elif state & 2:
yield s[si:ci - 1]
si = ci - 1
state = 4 | 8 | 16
ci += 1
elif c.isupper():
if state & 4:
yield s[si:ci]
si = ci
if state & 32:
state = 2 | 8 | 16 | 32
else:
state = 8 | 16 | 32
ci += 1
elif c.isdigit():
if state & 8:
yield s[si:ci]
si = ci
state = 1 | 4 | 16
ci += 1
else:
if state & 16:
yield s[si:ci]
state = 0
ci += 1 # eat ci
si = ci
print(' : ', c, bin(state))
if state:
yield s[si:ci]
def camelcaseToUnderscore(s):
return '_'.join(splitSymbol(s))
splitsymbol can parses all case types: UpperSEQUENCEInterleaved, under_score, BIG_SYMBOLS and cammelCasedMethods
I hope it is useful
You can also set processData to true:
collection.fetch({
data: { page: 1 },
processData: true
});
Jquery will auto process data object into param string,
but in Backbone.sync function, Backbone turn the processData off because Backbone will use other method to process data in POST,UPDATE...
in Backbone source:
if (params.type !== 'GET' && !Backbone.emulateJSON) {
params.processData = false;
}
<body oncontextmenu="return false">
Use this code to disable right click.
In C ++, if a const object is initialized with a constant expression, we can use our const object wherever a constant expression is required.
const int x = 10;
int a[x] = {0};
For example, we can make a case statement in switch.
constexpr can be used with arrays.
constexpr is not a type.
The constexpr keyword can be used in conjunction with the auto keyword.
constexpr auto x = 10;
struct Data { // We can make a bit field element of struct.
int a:x;
};
If we initialize a const object with a constant expression, the expression generated by that const object is now a constant expression as well.
Constant Expression : An expression whose value can be calculated at compile time.
x*5-4 // This is a constant expression. For the compiler, there is no difference between typing this expression and typing 46 directly.
Initialize is mandatory. It can be used for reading purposes only. It cannot be changed. Up to this point, there is no difference between the "const" and "constexpr" keywords.
NOTE: We can use constexpr and const in the same declaration.
constexpr const int* p;
Normally, the return value of a function is obtained at runtime. But calls to constexpr functions will be obtained as a constant in compile time when certain conditions are met.
NOTE : Arguments sent to the parameter variable of the function in function calls or to all parameter variables if there is more than one parameter, if C.E the return value of the function will be calculated in compile time. !!!
constexpr int square (int a){
return a*a;
}
constexpr int a = 3;
constexpr int b = 5;
int arr[square(a*b+20)] = {0}; //This expression is equal to int arr[35] = {0};
In order for a function to be a constexpr function, the return value type of the function and the type of the function's parameters must be in the type category called "literal type".
The constexpr functions are implicitly inline functions.
None of the constexpr functions need to be called with a constant expression.It is not mandatory. If this happens, the computation will not be done at compile time. It will be treated like a normal function call. Therefore, where the constant expression is required, we will no longer be able to use this expression.
1 ) The types used in the parameters of the function and the type of the return value of the function must be literal type.
2 ) A local variable with static life time should not be used inside the function.
3 ) If the function is legal, when we call this function with a constant expression in compile time, the compiler calculates the return value of the function in compile time.
4 ) The compiler needs to see the code of the function, so constexpr functions will almost always be in the header files.
5 ) In order for the function we created to be a constexpr function, the definition of the function must be in the header file.Thus, whichever source file includes that header file will see the function definition.
Normally with Default Member Initialization, static data members with const and integral types can be initialized within the class. However, in order to do this, there must be both "const" and "integral types".
If we use static constexpr then it doesn't have to be an integral type to initialize it inside the class. As long as I initialize it with a constant expression, there is no problem.
class Myclass {
const static int sx = 15; // OK
constexpr static int sy = 15; // OK
const static double sd = 1.5; // ERROR
constexpr static double sd = 1.5; // OK
};
To see the window height while (or after) it is resized, try it:
$(window).resize(function() {
$('body').prepend('<div>' + $(window).height() - 46 + '</div>');
});
First, install the URL Rewrite from a download or from the Web Platform Installer. Second, restart IIS. And, finally, close IIS and open again. The last step worked for me.
You can try this
SELECT * FROM Buses
WHERE BusID
in (1,2,3,4,...)
Warning: this is a convenience method to convert a JSON string to a dictionary if, for some reason, you have to work from a JSON string. But if you have the JSON data available, you should instead work with the data, without using a string at all.
Swift 3
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let str = "{\"name\":\"James\"}"
let dict = convertToDictionary(text: str)
Swift 2
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
let str = "{\"name\":\"James\"}"
let result = convertStringToDictionary(str)
Original Swift 1 answer:
func convertStringToDictionary(text: String) -> [String:String]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:String]
if error != nil {
println(error)
}
return json
}
return nil
}
let str = "{\"name\":\"James\"}"
let result = convertStringToDictionary(str) // ["name": "James"]
if let name = result?["name"] { // The `?` is here because our `convertStringToDictionary` function returns an Optional
println(name) // "James"
}
In your version, you didn't pass the proper parameters to NSJSONSerialization
and forgot to cast the result. Also, it's better to check for the possible error. Last note: this works only if your value is a String. If it could be another type, it would be better to declare the dictionary conversion like this:
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]
and of course you would also need to change the return type of the function:
func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }
From the composer help create-project
command
The create-project command creates a new project from a given
package into a new directory. If executed without params and in a directory with a composer.json file it installs the packages for the current project.
You can use this command to bootstrap new projects or setup a clean
version-controlled installation for developers of your project.[version]
You can also specify the version with the package name using = or : as separator.
To install unstable packages, either specify the version you want, or use the --stability=dev (where dev can be one of RC, beta, alpha or dev).
This command works:
composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist
This works with the * notation.
Yet another solution:
string s = "??"; // or whatever
if (chldNode.Attributes.Cast<XmlAttribute>()
.Select(x => x.Value)
.Contains(attributeName))
s = xe.Attributes[attributeName].Value;
It also avoids the exception when the expected attribute attributeName
actually doesn't exist.
Cloning Private Repository using HTTPS in Year 2020
If maintainer of repository has given Developer access to you on his private library ,you need to first login to https://gitlab.com/users/sign_in with user for which you have received invitation,you will be prompted to change your password,once you change your password then you can successfully clone repository ,pull and push changes to it.
If:
Then, you can pass a list of worksheet names. Which you could populate manually:
import pandas as pd
path = "C:\\Path\\To\\Your\\Data\\"
file = "data.xlsx"
sheet_lst_wanted = ["01_SomeName","05_SomeName","12_SomeName"] # tab names from Excel
### import and compile data ###
# read all sheets from list into an ordered dictionary
dict_temp = pd.read_excel(path+file, sheet_name= sheet_lst_wanted)
# concatenate the ordered dict items into a dataframe
df = pd.concat(dict_temp, axis=0, ignore_index=True)
OR
A bit of automation is possible if your desired worksheets have a common naming convention that also allows you to differentiate from unwanted sheets:
# substitute following block for the sheet_lst_wanted line in above block
import xlrd
# string common to only worksheets you want
str_like = "SomeName"
### create list of sheet names in Excel file ###
xls = xlrd.open_workbook(path+file, on_demand=True)
sheet_lst = xls.sheet_names()
### create list of sheets meeting criteria ###
sheet_lst_wanted = []
for s in sheet_lst:
# note: following conditional statement based on my sheets ending with the string defined in sheet_like
if s[-len(str_like):] == str_like:
sheet_lst_wanted.append(s)
else:
pass
We have experienced the same issue when moving the sql server in-house.
A good solution that we ended up using is splitting the sql file into chunks. There are several ways to do that. Use
http://www.ozerov.de/bigdump/ seems good (but never used it)
http://www.rusiczki.net/2007/01/24/sql-dump-file-splitter/ used it and it was very useful to get structure out of the mess and you can take it from there.
Hope this helps :)
Using toggle instead of hide, solved my problem
import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)
or use lambda
sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)
Yes you understood it correctly, the function password_hash() will generate a salt on its own, and includes it in the resulting hash-value. Storing the salt in the database is absolutely correct, it does its job even if known.
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($_POST['password'], PASSWORD_DEFAULT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($_POST['password'], $existingHashFromDb);
The second salt you mentioned (the one stored in a file), is actually a pepper or a server side key. If you add it before hashing (like the salt), then you add a pepper. There is a better way though, you could first calculate the hash, and afterwards encrypt (two-way) the hash with a server-side key. This gives you the possibility to change the key when necessary.
In contrast to the salt, this key should be kept secret. People often mix it up and try to hide the salt, but it is better to let the salt do its job and add the secret with a key.
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(
Convert.ToInt32(e.Row.Cells[7].Text.Substring(3,2))).Substring(0,3)
+ "-"
+ Convert.ToDateTime(e.Row.Cells[7].Text).ToString("yyyy");
Depending on how secure you need the configuration files or how reliable your application is, http://activemq.apache.org/encrypted-passwords.html may be a good solution for you.
If you are not too afraid of the password being decrypted and it can be really simple to configure using a bean to store the password key. However, if you need more security you can set an environment variable with the secret and remove it after launch. With this you have to worry about the application / server going down and not application not automatically relaunching.
Other than the common ones above, I had a multi-project solution to publish. Apparently some files target different frameworks.
So my solution: Properties > Specific Version (False)
I've found that experimenting with the various methods is a good sanity check even after having a good handle of what their various uses and capabilities are.
Towards that end I have found this website extremely useful to confirm my suspicions that I am doing something appropriately. It has also proven useful for decoding an encodeURIComponent'ed string which can be rather challenging to interpret. A great bookmark to have:
Update 2:
Xcode 9 appears to have a "feature" where it will ignore the file's current line endings, and instead just use your default line-ending setting when inserting lines into a file, resulting in files with mixed line endings.
I'm pretty sure this bug didn't exist in Xcode 7; not sure about Xcode 8. The good news is that it appears to be fixed in Xcode 10.
For the time it existed, this bug caused a small amount of hilarity in the codebase I refer to in the question (which to this day uses autocrlf=false
), and led to many "EOL" commit messages and eventually to my writing a git pre-commit
hook to check for/prevent introducing mixed line endings.
Update:
Note: As noted by VonC, starting from Git 2.8, merge markers will not introduce Unix-style line-endings to a Windows-style file.
Original:
One little hiccup that I've noticed with this setup is that when there are merge conflicts, the lines git adds to mark up the differences do not have Windows line-endings, even when the rest of the file does, and you can end up with a file with mixed line endings, e.g.:
// Some code<CR><LF>
<<<<<<< Updated upstream<LF>
// Change A<CR><LF>
=======<LF>
// Change B<CR><LF>
>>>>>>> Stashed changes<LF>
// More code<CR><LF>
This doesn't cause us any problems (I imagine any tool that can handle both types of line-endings will also deal sensible with mixed line-endings--certainly all the ones we use do), but it's something to be aware of.
The other thing* we've found, is that when using git diff
to view changes to a file that has Windows line-endings, lines that have been added display their carriage returns, thus:
// Not changed
+ // New line added in^M
+^M
// Not changed
// Not changed
* It doesn't really merit the term: "issue".
Posting my full function based on Kindall's solution. I was able to support any alphanumeric characters mixed in with the numbers by padding each version section with leading zeros.
While certainly not as pretty as his one-liner function, it seems to work well with alpha-numeric version numbers. (Just be sure to set the zfill(#)
value appropriately if you have long strings in your versioning system.)
def versiontuple(v):
filled = []
for point in v.split("."):
filled.append(point.zfill(8))
return tuple(filled)
.
>>> versiontuple("10a.4.5.23-alpha") > versiontuple("2a.4.5.23-alpha")
True
>>> "10a.4.5.23-alpha" > "2a.4.5.23-alpha"
False
You can't use for
/in
on NodeList
s or HTMLCollection
s. However, you can use some Array.prototype
methods, as long as you .call()
them and pass in the NodeList
or HTMLCollection
as this
.
So consider the following as an alternative to jfriend00's for
loop:
var list= document.getElementsByClassName("events");
[].forEach.call(list, function(el) {
console.log(el.id);
});
There's a good article on MDN that covers this technique. Note their warning about browser compatibility though:
[...] passing a host object (like a
NodeList
) asthis
to a native method (such asforEach
) is not guaranteed to work in all browsers and is known to fail in some.
So while this approach is convenient, a for
loop may be the most browser-compatible solution.
Update (Aug 30, 2014): Eventually you'll be able to use ES6 for
/of
!
var list = document.getElementsByClassName("events");
for (const el of list)
console.log(el.id);
It's already supported in recent versions of Chrome and Firefox.
You will need to save the Docker image as a tar file:
docker save -o <path for generated tar file> <image name>
Then copy your image to a new system with regular file transfer tools such as cp
, scp
or rsync
(preferred for big files). After that you will have to load the image into Docker:
docker load -i <path to image tar file>
PS: You may need to sudo
all commands.
EDIT: You should add filename (not just directory) with -o, for example:
docker save -o c:/myfile.tar centos:16
Or you can use for the HttpClient in the Windows.Web.Http
namespace:
var filter = new HttpBaseProtocolFilter();
#if DEBUG
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
#endif
using (var httpClient = new HttpClient(filter)) {
...
}
To take an export to your local system from sql developer.
Path : C:\Source_Table_Extract\des_loan_due_dtls_src_boaf.csv
SPOOL "Path where you want to save the file"
SELECT /*csv*/ * FROM TABLE_NAME;
Oracle provides some simple examples:
http://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html#CHDJBGFC
Assuming you are in ~/ and the java source tree is in ./saxon_source/net and you want to recurse through the whole source tree net is both a directory and the top package name.
mkdir saxon_docs
javadoc -d saxon_docs -sourcepath saxon_source -subpackages net
myString.Remove(myString.Length-3);
Don't use while True and break statements. It's bad programming.
Imagine you come to debug someone else's code and you see a while True on line 1 and then have to trawl your way through another 200 lines of code with 15 break statements in it, having to read umpteen lines of code for each one to work out what actually causes it to get to the break. You'd want to kill them...a lot.
The condition that causes a while loop to stop iterating should always be clear from the while loop line of code itself without having to look elsewhere.
Phil has the "correct" solution, as it has a clear end condition right there in the while loop statement itself.
You could try "Clean Tomcat Work Directory" or simply "Clean..". This supposed to discard all published state and republish from scratch.
I got here searching for a way to execute some code whenever the program ends.
Found this:
Kernel.at_exit { puts "sayonara" }
# do whatever
# [...]
# call #exit or #abort or just let the program end
# calling #exit! will skip the call
Called multiple times will register multiple handlers.
Both of these operations restore a set of files to a previous state and are essentially faster, safer ways of undoing mistakes than using the p4 obliterate
command (and you don't need admin access to use them).
In the case of "Rollback...", this could be any number of files, even an entire depot. You can tell it to rollback to a specific revision, changelist, or label. The files are restored to the state they were in at the time of creation of that revision, changelist, or label.
In the case of "Back Out Submitted Changelist #####", the restore operation is restricted to the files that were submitted in changelist #####. Those files are restored to the state they were in before you submitted that changelist, provided no changes have been made to those files since. If subsequent changes have been made to any of those files, Perforce will tell you that those files are now out of date. You will have to sync to the head revision and then resolve the differences. This way you don't inadvertently clobber any changes that you actually want to keep.
Both operations work by essentially submitting old revisions as new revisions. When you perform a "Rollback...", you are restoring the files to the state they were in at a specific point in time, regardless of what has happened to them since. When you perform a "Back out...", you are attempting to undo the changes you made at a specific point in time, while maintaining the changes that have occurred since.
I just use for _ in range(n)
, it's straight to the point. It's going to generate the entire list for huge numbers in Python 2, but if you're using Python 3 it's not a problem.
Suppose I have Hashmap with key datatype as KeyDataType and value datatype as ValueDataType
HashMap<KeyDataType,ValueDataType> list;
Add all items you needed to it. Now you can retrive all hashmap keys to a list by.
KeyDataType[] mKeys;
mKeys=list.keySet().toArray(new KeyDataType[list.size()]);
So, now you got your all keys in an array mkeys[]
you can now retrieve any value by calling
list.get(mkeys[position]);
Using .multiply() (ufunc multiply)
a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0
np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])
A module is a single file (or files) that are imported under one import and used. e.g.
import my_module
A package is a collection of modules in directories that give a package hierarchy.
from my_package.timing.danger.internets import function_of_love
you can use the has_key()
method:
if dict.has_key('xyz')==1:
#update the value for the key
else:
pass
Strings in python are immutable, so you cannot treat them as a list and assign to indices.
Use .replace()
instead:
line = line.replace(';', ':')
If you need to replace only certain semicolons, you'll need to be more specific. You could use slicing to isolate the section of the string to replace in:
line = line[:10].replace(';', ':') + line[10:]
That'll replace all semi-colons in the first 10 characters of the string.
You can use one of the following.
$!
is the PID of the last backgrounded process.kill -0 $PID
checks whether it's still running.$$
is the PID of the current shell.try this , it works 100 % : add columns and rows programatically : you need to create item class at first :
public class Item
{
public int Num { get; set; }
public string Start { get; set; }
public string Finich { get; set; }
}
private void generate_columns()
{
DataGridTextColumn c1 = new DataGridTextColumn();
c1.Header = "Num";
c1.Binding = new Binding("Num");
c1.Width = 110;
dataGrid1.Columns.Add(c1);
DataGridTextColumn c2 = new DataGridTextColumn();
c2.Header = "Start";
c2.Width = 110;
c2.Binding = new Binding("Start");
dataGrid1.Columns.Add(c2);
DataGridTextColumn c3 = new DataGridTextColumn();
c3.Header = "Finich";
c3.Width = 110;
c3.Binding = new Binding("Finich");
dataGrid1.Columns.Add(c3);
dataGrid1.Items.Add(new Item() { Num = 1, Start = "2012, 8, 15", Finich = "2012, 9, 15" });
dataGrid1.Items.Add(new Item() { Num = 2, Start = "2012, 12, 15", Finich = "2013, 2, 1" });
dataGrid1.Items.Add(new Item() { Num = 3, Start = "2012, 8, 1", Finich = "2012, 11, 15" });
}
The .cpp
file is configured to use precompiled header, therefore it must be included first (before iostream). For Visual Studio, it's name is usually "stdafx.h".
If there are no stdafx* files in your project, you need to go to this file's options and set it as “Not using precompiled headers”.
Many of the answers here are out of date for 2015 (although the initially accepted one from Daniel Roseman is not). Here's the current state of things:
.whl
files)—not just on PyPI, but in third-party repositories like Christoph Gohlke's Extension Packages for Windows. pip
can handle wheels; easy_install
cannot.virtualenv
) have become a very important and prominent tool (and recommended in the official docs); they include pip
out of the box, but don't even work properly with easy_install
.distribute
package that included easy_install
is no longer maintained. Its improvements over setuptools
got merged back into setuptools
. Trying to install distribute
will just install setuptools
instead.easy_install
itself is only quasi-maintained.pip
used to be inferior to easy_install
—installing from an unpacked source tree, from a DVCS repo, etc.—are long-gone; you can pip install .
, pip install git+https://
.pip
comes with the official Python 2.7 and 3.4+ packages from python.org, and a pip
bootstrap is included by default if you build from source.pip
as "the preferred installer program".pip
over the years that will never be in easy_install
. For example, pip
makes it easy to clone your site-packages by building a requirements file and then installing it with a single command on each side. Or to convert your requirements file to a local repo to use for in-house development. And so on.The only good reason that I know of to use easy_install
in 2015 is the special case of using Apple's pre-installed Python versions with OS X 10.5-10.8. Since 10.5, Apple has included easy_install
, but as of 10.10 they still don't include pip
. With 10.9+, you should still just use get-pip.py
, but for 10.5-10.8, this has some problems, so it's easier to sudo easy_install pip
. (In general, easy_install pip
is a bad idea; it's only for OS X 10.5-10.8 that you want to do this.) Also, 10.5-10.8 include readline
in a way that easy_install
knows how to kludge around but pip
doesn't, so you also want to sudo easy_install readline
if you want to upgrade that.
To add to add to the previous answer, there is even a fourth way that can be used
import codecs
encoded4 = codecs.encode(original, 'utf-8')
print(encoded4)
You don't have a jQuery refresh function, because this is JavaScript basics.
Try this:
<body onload="if (location.href.indexOf('reload')==-1) location.replace(location.href+'?reload');">
Add the sheet name infront of the cell, e.g.:
=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")
Assumes the sheet name is "stock"
You may also use:
try
{
// Dangerous code
}
finally
{
// clean up, or do nothing
}
And any exceptions thrown will bubble up to the next level that handles them.
If you want a code that is readable by all programmers (c++, java, and others) use the original old form instead of cryptographic new features
atp::ta::DataDrawArrayInfo* ddai;
for(size_t i = 0; i < m_dataDraw->m_dataDrawArrayInfoList.size(); i++) {
ddai = m_dataDraw->m_dataDrawArrayInfoList[i];
//...
}
I would retrieve the time from the DB in a raw form (long timestamp or java's Date), and then use SimpleDateFormat to format it, or Calendar to manipulate it. In both cases you should set the timezone of the objects before using it.
See SimpleDateFormat.setTimeZone(..)
and Calendar.setTimeZone(..)
for details
Set envirionment variable STUDIO_JDK
(java_home
outputs the Java home dir and sed
strips two folders to get the jdk dir)
launchctl setenv STUDIO_JDK `/usr/libexec/java_home -version 1.8 | sed 's/\/Contents\/Home//g'`
Launch Android Studio like you would normally
The above steps only works for the current session. Here is how to create a plist file in /Library/LaunchDaemons that runs the above command on every boot:
sudo defaults write /Library/LaunchDaemons/com.google.studiojdk Label STUDIO_JDK
sudo defaults write /Library/LaunchDaemons/com.google.studiojdk ProgramArguments -array /bin/launchctl setenv STUDIO_JDK `/usr/libexec/java_home | sed 's/\/Contents\/Home//g'`
sudo defaults write /Library/LaunchDaemons/com.google.studiojdk RunAtLoad -bool TRUE
Found out about the plist trick thanks to http://www.dowdandassociates.com/blog/content/howto-set-an-environment-variable-in-mac-os-x-launchd-plist/
If you want to use less code, you can also use the norm
in the stats
package (the 'F' stands for Forbenius, which is the Euclidean norm):
norm(matrix(x1-x2), 'F')
While this may look a bit neater, it's not faster. Indeed, a quick test on very large vectors shows little difference, though so12311's method is slightly faster. We first define:
set.seed(1234)
x1 <- rnorm(300000000)
x2 <- rnorm(300000000)
Then testing for time yields the following:
> system.time(a<-sqrt(sum((x1-x2)^2)))
user system elapsed
1.02 0.12 1.18
> system.time(b<-norm(matrix(x1-x2), 'F'))
user system elapsed
0.97 0.33 1.31
This is easiest with a library like jQuery:
<input type="button" onClick="javascript:test_byid();" value="id='second'" />
<script>
function test_byid()
{
$("#second").toggleClass("highlight");
}
</script>
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
You could do this two different ways. One is by using "as"
has_many :tasks, :as => :jobs
or
def jobs
self.tasks
end
Obviously the first one would be the best way to handle it.
Use the same way to protect binary file of c/c++, that is, obfuscate each function body in executable or library binary file, insert an instruction "jump" at the begin of each function entry, jump to special function to restore obfuscated code. Byte-code is binary code of Python script, so
0 JUMP_ABSOLUTE n = 3 + len(bytecode) 3 ... ... Here it's obfuscated bytecode ... n LOAD_GLOBAL ? (__pyarmor__) n+3 CALL_FUNCTION 0 n+6 POP_TOP n+7 JUMP_ABSOLUTE 0
Those obfuscated file (.pyc or .pyo) can be used by normal python interpreter, when those code object is called first time
First op is JUMP_ABSOLUTE, it will jump to offset n
At offset n, the instruction is to call a PyCFunction. This function will restore those obfuscated bytecode between offset 3 and n, and put the original byte-code at offset 0. The obfuscated code can be got by the following code
char *obfucated_bytecode; Py_ssize_t len; PyFrameObject* frame = PyEval_GetFrame(); PyCodeObject *f_code = frame->f_code; PyObject *co_code = f_code->co_code; PyBytes_AsStringAndSize(co_code, &obfucated_bytecode, &len)
After this function returns, the last instruction is to jump to offset 0. The really byte-code now is executed.
There is a tool Pyarmor to obfuscate python scripts by this way.
As many answers pointed this out: You build Dockerfile to get an image and you run image to get a container.
However, following steps helped me get a better feel for what Docker image and container are:
1) Build Dockerfile:
docker build -t my_image dir_with_dockerfile
2) Save the image to .tar
file
docker save -o my_file.tar my_image_id
my_file.tar
will store the image. Open it with tar -xvf my_file.tar
, and you will get to see all the layers. If you dive deeper into each layer you can see what changes were added in each layer. (They should be pretty close to commands in the Dockerfile).
3) To take a look inside of a container, you can do:
sudo docker run -it my_image bash
and you can see that is very much like an OS.
So this is my final code after googling for 2 days on how to add a namespace and make soap request along with the SOAP envelope without adding proxy/Service Reference
class Request
{
public static void Execute(string XML)
{
try
{
HttpWebRequest request = CreateWebRequest();
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(AppendEnvelope(AddNamespace(XML)));
using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
Console.WriteLine(soapResult);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private static HttpWebRequest CreateWebRequest()
{
string ICMURL = System.Configuration.ConfigurationManager.AppSettings.Get("ICMUrl");
HttpWebRequest webRequest = null;
try
{
webRequest = (HttpWebRequest)WebRequest.Create(ICMURL);
webRequest.Headers.Add(@"SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return webRequest;
}
private static string AddNamespace(string XML)
{
string result = string.Empty;
try
{
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(XML);
XmlElement temproot = xdoc.CreateElement("ws", "Request", "http://example.com/");
temproot.InnerXml = xdoc.DocumentElement.InnerXml;
result = temproot.OuterXml;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return result;
}
private static string AppendEnvelope(string data)
{
string head= @"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" ><soapenv:Header/><soapenv:Body>";
string end = @"</soapenv:Body></soapenv:Envelope>";
return head + data + end;
}
}
The (un)safe way to do this - if you are ok with not using option explicit - is...
Not TypeName(myObj) = "Empty"
This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...
Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ true, the object exists - TypeName is Object
'Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ false, the object has not been declared
This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.
use sequenty.
sudo npm install sequenty
or
https://github.com/AndyShin/sequenty
very simple.
var sequenty = require('sequenty');
function f1(cb) // cb: callback by sequenty
{
console.log("I'm f1");
cb(); // please call this after finshed
}
function f2(cb)
{
console.log("I'm f2");
cb();
}
sequenty.run([f1, f2]);
also you can use a loop like this:
var f = [];
var queries = [ "select .. blah blah", "update blah blah", ...];
for (var i = 0; i < queries.length; i++)
{
f[i] = function(cb, funcIndex) // sequenty gives you cb and funcIndex
{
db.query(queries[funcIndex], function(err, info)
{
cb(); // must be called
});
}
}
sequenty.run(f); // fire!
Put this line at the top of your source
# -*- coding: utf-8 -*-
If your editor uses a different encoding, substitute for utf-8
Then you can include utf-8 characters directly in the source
There's no way to actively detect if there's a zoom. I found a good entry here on how you can attempt to implement it.
I’ve found two ways of detecting the zoom level. One way to detect zoom level changes relies on the fact that percentage values are not zoomed. A percentage value is relative to the viewport width, and thus unaffected by page zoom. If you insert two elements, one with a position in percentages, and one with the same position in pixels, they’ll move apart when the page is zoomed. Find the ratio between the positions of both elements and you’ve got the zoom level. See test case. http://web.archive.org/web/20080723161031/http://novemberborn.net/javascript/page-zoom-ff3
You could also do it using the tools of the above post. The problem is you're more or less making educated guesses on whether or not the page has zoomed. This will work better in some browsers than other.
There's no way to tell if the page is zoomed if they load your page while zoomed.
That's because at the time of installation you have selected the default radio button to use "Git" with the "Git bash" only. If you would have chosen "Git and command line tool" than this would not be an issue.
1 byte may hold 1 character. For Example: Refer Ascii values for each character & convert into binary. This is how it works.
value 255 is stored as (11111111) base 2. Visit this link for knowing more about binary conversion. http://acc6.its.brooklyn.cuny.edu/~gurwitz/core5/nav2tool.html
Size of Tiny Int = 1 Byte ( -128 to 127)
Int = 4 Bytes (-2147483648 to 2147483647)
If you mean the screen where you have that interpreter prompt >>>
you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do
import os
os.system('cls') # on windows
or
os.system('clear') # on linux / os x
I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.
Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))
I tried to get this working using FINDSTR, but for some reason my "debugging" command always output an error level of 0:
ECHO %ERRORLEVEL%
My workaround is to use Grep from Cygwin, which outputs the right errorlevel (it will give an errorlevel greater than 0) if a string is not found:
dir c:\*.tib >out 2>>&1
grep "1 File(s)" out
IF %ERRORLEVEL% NEQ 0 "Run other commands" ELSE "Run Errorlevel 0 commands"
Cygwin's grep will also output errorlevel 2 if the file is not found. Here's the hash from my version:
C:\temp\temp>grep --version grep (GNU grep) 2.4.2
C:\cygwin64\bin>md5sum grep.exe c0a50e9c731955628ab66235d10cea23 *grep.exe
C:\cygwin64\bin>sha1sum grep.exe ff43a335bbec71cfe99ce8d5cb4e7c1ecdb3db5c *grep.exe
You are using DictWriter.writerows()
which expects a list of dicts, not a dict. You want DictWriter.writerow()
to write a single row.
You will also want to use DictWriter.writeheader()
if you want a header for you csv file.
You also might want to check out the with
statement for opening files. It's not only more pythonic and readable but handles closing for you, even when exceptions occur.
Example with these changes made:
import csv
my_dict = {"test": 1, "testing": 2}
with open('mycsvfile.csv', 'w') as f: # You will need 'wb' mode in Python 2.x
w = csv.DictWriter(f, my_dict.keys())
w.writeheader()
w.writerow(my_dict)
Which produces:
test,testing
1,2
I'm using Rails + Cucumber + Selenium Webdriver + PhantomJS, and I've been using a monkey-patched version of Selenium Webdriver, which keeps PhantomJS browser open between test runs. See this blog post: http://blog.sharetribe.com/2014/04/07/faster-cucumber-startup-keep-phantomjs-browser-open-between-tests/
See also my answer to this post: How do I execute a command on already opened browser from a ruby file
I found another case where jquery gives you status code 0 -- if for some reason XMLHttpRequest is not defined, you'll get this error.
Obviously this won't normally happen on the web, but a bug in a nightly firefox build caused this to crop up in an add-on I was writing. :)
Using your example, you could do:
public void doit(A a) {
if(a instanceof B) {
// needs to cast to B to access draw2 which isn't present in A
// note that this is probably not a good OO-design, but that would
// be out-of-scope for this discussion :)
((B)a).draw2();
}
a.draw();
}
As many have already told you:
mainList.get(3);
Be sure to check the ArrayList Javadoc.
Also, be careful with the arrays indices: in Java, the first element is at index 0
. So if you are trying to get the third element, your solution would be mainList.get(2);
I would agree with @evillinux, It would be best to make your background image semi transparent so it supports < ie8
The other suggestions of using another div are also a great option, and it's the way to go if you want to do this in css. For example if the site had such features as selecting your own background color. I would suggest using a filter for older IE. eg:
filter:Alpha(opacity=50)
I've been using this function in my project.
function changeViewPort(key, val) {
var reg = new RegExp(key, "i"), oldval = document.querySelector('meta[name="viewport"]').content;
var newval = reg.test(oldval) ? oldval.split(/,\s*/).map(function(v){ return reg.test(v) ? key+"="+val : v; }).join(", ") : oldval+= ", "+key+"="+val ;
document.querySelector('meta[name="viewport"]').content = newval;
}
so just addEventListener:
if( /iPad|iPhone|iPod|Android/i.test(navigator.userAgent) ){
window.addEventListener("orientationchange", function() {
changeViewPort("maximum-scale", 1);
changeViewPort("maximum-scale", 10);
}
}
For a unique column, use this:
INSERT OR REPLACE INTO table () values();
For more information, see: sqlite.org/lang_insert
First of all, it's actually not accurate to say that
x % 2 == x & 1
Simple counterexample: x = -1
. In many languages, including Java, -1 % 2 == -1
. That is, %
is not necessarily the traditional mathematical definition of modulo. Java calls it the "remainder operator", for example.
With regards to bitwise optimization, only modulo powers of two can "easily" be done in bitwise arithmetics. Generally speaking, only modulo powers of base b can "easily" be done with base b representation of numbers.
In base 10, for example, for non-negative N
, N mod 10^k
is just taking the least significant k
digits.
Walkthrough Steps
Running the following command will update the repo to use HTTP rather than HTTPS:
sudo sed -i "s/mirrorlist=https/mirrorlist=http/" /etc/yum.repos.d/epel.repo
You should then be able to update with this command:
yum -y update
Sorry to beat a dead horse, but it is kind-of weird that no-one pointed this out - "Yes you can, but this is the opposite of how you use capturing groups in real life".
If you use Regex the way it is meant to be used, the solution is as simple as this:
"6 example input 4".replaceAll("(?:\\d)(.*)(?:\\d)", "number$11");
Or as rightfully pointed out by shmosel below,
"6 example input 4".replaceAll("\d(.*)\d", "number$11");
...since in your regex there is no good reason to group the decimals at all.
You don't usually use capturing groups on the parts of the string you want to discard, you use them on the part of the string you want to keep.
If you really want groups that you want to replace, what you probably want instead is a templating engine (e.g. moustache, ejs, StringTemplate, ...).
As an aside for the curious, even non-capturing groups in regexes are just there for the case that the regex engine needs them to recognize and skip variable text. For example, in
(?:abc)*(capture me)(?:bcd)*
you need them if your input can look either like "abcabccapture mebcdbcd" or "abccapture mebcd" or even just "capture me".
Or to put it the other way around: if the text is always the same, and you don't capture it, there is no reason to use groups at all.
Answer corresponding to this by @Brad Parks Not sure about the MySQL version, but mine was 5.6, hence a little bit tweaking works:
I created a function debug_msg
which is function (not procedure) and returns text(no character limit) and then call the function as SELECT debug_msg
(params) AS my_res_set
, code as below:
CREATE DEFINER=`root`@`localhost` FUNCTION `debug_msg`(`enabled` INT(11), `msg` TEXT) RETURNS text CHARSET latin1
READS SQL DATA
BEGIN
IF enabled=1 THEN
return concat('** DEBUG:', "** ", msg);
END IF;
END
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_func_call`(
IN RegionID VARCHAR(20),
IN RepCurrency INT(11),
IN MGID INT(11),
IN VNC VARCHAR(255)
)
BEGIN
SET @enabled = TRUE;
SET @mainQuery = "SELECT * FROM Users u";
SELECT `debug_msg`(@enabled, @mainQuery) AS `debug_msg1`;
SET @lastQuery = CONCAT(@mainQuery, " WHERE u.age>30);
SELECT `debug_msg`(@enabled, @lastQuery) AS `debug_msg2`;
END $$
DELIMITER
Spring AOP and annotation based solution:
Usage (@RetryOperation
is our custom annotation for the job):
@RetryOperation(retryCount = 1, waitSeconds = 10)
boolean someMethod() throws Exception {
}
We'll need two things to accomplish this: 1. an annotation interface, and 2. a spring aspect. Here's one way to implement these:
The Annotation Interface:
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RetryOperation {
int retryCount();
int waitSeconds();
}
The Spring Aspect:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect @Component
public class RetryAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(RetryAspect.class);
@Around(value = "@annotation(RetryOperation)")
public Object retryOperation(ProceedingJoinPoint joinPoint) throws Throwable {
Object response = null;
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
RetryOperation annotation = method.getAnnotation(RetryOperation.class);
int retryCount = annotation.retryCount();
int waitSeconds = annotation.waitSeconds();
boolean successful = false;
do {
try {
response = joinPoint.proceed();
successful = true;
} catch (Exception ex) {
LOGGER.info("Operation failed, retries remaining: {}", retryCount);
retryCount--;
if (retryCount < 0) {
throw ex;
}
if (waitSeconds > 0) {
LOGGER.info("Waiting for {} second(s) before next retry", waitSeconds);
Thread.sleep(waitSeconds * 1000l);
}
}
} while (!successful);
return response;
}
}
From the Developer Guide:
android:id="@+id/my_button"
The at-symbol (@
) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+
) means that this is a new resource name that must be created and added to our resources (in the R.java
file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android
package namespace, like so:
android:id="@android:id/empty"
Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(-1)
Just add two lines in your php.ini file.
extension=php_openssl.dll
allow_url_include = On
its working for me.
You can use this example to handle your problem:
System.out.printf( "%-15s %15s %n", "name", "lastname");
System.out.printf( "%-15s %15s %n", "Bill", "Smith");
You can play with the "%" until you find the right alignment to satisfy your needs
Option 1
: Declare a struct with an int and string and return a struct variable.
struct foo {
int bar1;
char bar2[MAX];
};
struct foo fun() {
struct foo fooObj;
...
return fooObj;
}
Option 2
: You can pass one of the two via pointer and make changes to the actual parameter through the pointer and return the other as usual:
int fun(char **param) {
int bar;
...
strcpy(*param,"....");
return bar;
}
or
char* fun(int *param) {
char *str = /* malloc suitably.*/
...
strcpy(str,"....");
*param = /* some value */
return str;
}
Option 3
: Similar to the option 2. You can pass both via pointer and return nothing from the function:
void fun(char **param1,int *param2) {
strcpy(*param1,"....");
*param2 = /* some calculated value */
}
Maybe you can try the followings $indent -kr -i8 *.c
Hope it's useful for you!
Just define the target page in the action
attribute of the <form>
containing the submit button.
So, in page1.jsp
:
<form action="page2.jsp">
<input type="submit">
</form>
Unrelated to the problem, a JSP is not the best place to do business stuff, if you need to do any. Consider learning servlets.
The fastest and more flexible way to do that is passing the parent to the children from the constructor as below:
Declare a property in the parent form:
public string MyProperty {get; set;}
Declare a property from the parent in child form:
private ParentForm ParentProperty {get; set;}
Write the child's constructor like this:
public ChildForm(ParentForm parent){
ParentProperty= parent;
}
Change the value of the parent property everywhere in the child form:
ParentProperty.MyProperty = "New value";
It's done. the property MyProperty
in the parent form is changed. With this solution, you can change multiple properties from the child form. So delicious, no?!
There are many paths through your code whereby your variables are not initialized, which is why the compiler complains.
Specifically, you are not validating the user input for creditPlan
- if the user enters a value of anything else than "0","1","2" or "3"
, then none of the branches indicated will be executed (and creditPlan
will not be defaulted to zero as per your user prompt).
As others have mentioned, the compiler error can be avoided by either a default initialization of all derived variables before the branches are checked, OR ensuring that at least one of the branches is executed (viz, mutual exclusivity of the branches, with a fall through else
statement).
I would however like to point out other potential improvements:
CreditPlan
appears to have a finite domain and is better suited to an enumeration
or Dictionary
than a string
. Financial data and percentages should always be modelled as decimal
, not double
to avoid rounding issues, and 'status' appears to be a boolean.monthlyCharge = balance * annualRate * (1/12))
is common to more than one branch. For maintenance reasons, do not duplicate this code.e.g. here is an alternative representation of your model:
// Keep all Credit Plan parameters together in a model
public class CreditPlan
{
public Func<decimal, decimal, decimal> MonthlyCharge { get; set; }
public decimal AnnualRate { get; set; }
public Func<bool, Decimal> LateFee { get; set; }
}
// DRY up repeated calculations
static private decimal StandardMonthlyCharge(decimal balance, decimal annualRate)
{
return balance * annualRate / 12;
}
public static Dictionary<int, CreditPlan> CreditPlans = new Dictionary<int, CreditPlan>
{
{ 0, new CreditPlan
{
AnnualRate = .35M,
LateFee = _ => 0.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 1, new CreditPlan
{
AnnualRate = .30M,
LateFee = late => late ? 0 : 25.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 2, new CreditPlan
{
AnnualRate = .20M,
LateFee = late => late ? 0 : 35.0M,
MonthlyCharge = (balance, annualRate) => balance > 100
? balance * annualRate / 12
: 0
}
},
{ 3, new CreditPlan
{
AnnualRate = .15M,
LateFee = _ => 0.0M,
MonthlyCharge = (balance, annualRate) => balance > 500
? (balance - 500) * annualRate / 12
: 0
}
}
};
Think about somebody doing help(yourmodule)
at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help
in terms of amount of information). So if you have in x.py
:
"""This module does blah blah."""
class Blah(object):
"""This class does blah blah."""
then:
>>> import x; help(x)
shows:
Help on module x:
NAME
x - This module does blah blah.
FILE
/tmp/x.py
CLASSES
__builtin__.object
Blah
class Blah(__builtin__.object)
| This class does blah blah.
|
| Data and other attributes defined here:
|
| __dict__ = <dictproxy object>
| dictionary for instance variables (if defined)
|
| __weakref__ = <attribute '__weakref__' of 'Blah' objects>
| list of weak references to the object (if defined)
As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).
I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.
It calculates ex for each x in your list where e is Euler's number (approximately 2.718). In other words, np.exp(range(5))
is similar to [math.e**x for x in range(5)]
.
Just to clear some things up here. The answer that was accepted does not do the same as PHP in_array.
To do the same as PHP in_array use following expression:
{% if myVar in myArray %}
If you want to negate this you should use this:
{% if myVar not in myArray %}
To flatten a MultiIndex inside a chain of other DataFrame methods, define a function like this:
def flatten_index(df):
df_copy = df.copy()
df_copy.columns = ['_'.join(col).rstrip('_') for col in df_copy.columns.values]
return df_copy.reset_index()
Then use the pipe
method to apply this function in the chain of DataFrame methods, after groupby
and agg
but before any other methods in the chain:
my_df \
.groupby('group') \
.agg({'value': ['count']}) \
.pipe(flatten_index) \
.sort_values('value_count')
import datetime
int(datetime.datetime.today().strftime('%w'))+1
this should give you your real day number - 1 = sunday, 2 = monday, etc...
I had some difficulty using the solutions already suggested for my specific use case, but figured it out eventually. I don't think my specific case is worthy of a new question, so I am posting my solution here for reference. (This is very closely related to the question and provides a solution for anyone else with a similar case to mine).
The code I ended up with looks like this:
public class HideableControl<T>: Control where T: class
{
private string _propertyName;
private PropertyInfo _propertyInfo;
public string PropertyName
{
get { return _propertyName; }
set
{
_propertyName = value;
_propertyInfo = typeof(T).GetProperty(value);
}
}
protected override bool GetIsVisible(IRenderContext context)
{
if (_propertyInfo == null)
return false;
var model = context.Get<T>();
if (model == null)
return false;
return (bool)_propertyInfo.GetValue(model, null);
}
protected void SetIsVisibleProperty(Expression<Func<T, bool>> propertyLambda)
{
var expression = propertyLambda.Body as MemberExpression;
if (expression == null)
throw new ArgumentException("You must pass a lambda of the form: 'vm => vm.Property'");
PropertyName = expression.Member.Name;
}
}
public interface ICompanyViewModel
{
string CompanyName { get; }
bool IsVisible { get; }
}
public class CompanyControl: HideableControl<ICompanyViewModel>
{
public CompanyControl()
{
SetIsVisibleProperty(vm => vm.IsVisible);
}
}
The important part for me is that in the CompanyControl
class the compiler will only allow me to choose a boolean property of ICompanyViewModel
which makes it easier for other developers to get it right.
The main difference between my solution and the accepted answer is that my class is generic and I only want to match properties from the generic type that are boolean.
For your iphone You could use in your head balise :
"width=device-width"
return
returns a value. It doesn't matter what name you gave to that value. Returning it just "passes it out" so that something else can use it. If you want to use it, you have to grab it from outside:
lst = defineAList()
useTheList(lst)
Returning list
from inside defineAList
doesn't mean "make it so the whole rest of the program can use that variable". It means "pass this variable out and give the rest of the program one chance to grab it and use it". You need to assign that value to something outside the function in order to make use of it. Also, because of this, there is no need to define your list ahead of time with list = []
. Inside defineAList
, you create a new list and return it; this list has no relationship to the one you defined with list = []
at the beginning.
Incidentally, I changed your variable name from list
to lst
. It's not a good idea to use list
as a variable name because that is already the name of a built-in Python type. If you make your own variable called list
, you won't be able to access the builtin one anymore.
Normally, you run IE 32 bit.
However, on 64-bit versions of Windows, there is a separate link in the Start Menu to Internet Explorer (64 bit). There's no real reason to use it, though.
In Help, About, the 64-bit version of IE will say 64-bit Edition
(just after the full version string).
The 32-bit and 64-bit versions of IE have separate addons lists (because 32-bit addons cannot be loaded in 64-bit IE, and vice-versa), so you should make sure that Java appears on both lists.
In general, you can tell whether a process is 32-bit or 64-bit by right-clicking the application in Task Manager and clicking Go To Process. 32-bit processes will end with *32
.
Don't forget to check whether the string is empty or null
. If we forget checking null
or empty then we would get NullPointerException
or StringIndexOutOfBoundException
if a given String is null or empty.
public class StartWithUpperCase{
public static void main(String[] args){
String str1 = ""; //StringIndexOfBoundException if
//empty checking not handled
String str2 = null; //NullPointerException if
//null checking is not handled.
String str3 = "Starts with upper case";
String str4 = "starts with lower case";
System.out.println(startWithUpperCase(str1)); //false
System.out.println(startWithUpperCase(str2)); //false
System.out.println(startWithUpperCase(str3)); //true
System.out.println(startWithUpperCase(str4)); //false
}
public static boolean startWithUpperCase(String givenString){
if(null == givenString || givenString.isEmpty() ) return false;
else return (Character.isUpperCase( givenString.codePointAt(0) ) );
}
}
I highly suggest you to use an array instead of an object if you're doing react itteration, this is a syntax I use it ofen.
const rooms = this.state.array.map((e, i) =>(<div key={i}>{e}</div>))
To use the element, just place {rooms}
in your jsx.
Where e=elements of the arrays and i=index of the element. Read more here. If your looking for itteration, this is the way to do it.
Maybe try something like:
import matplotlib.pyplot as plt
import numpy
from scipy import stats
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
density = stats.kde.gaussian_kde(data)
x = numpy.arange(0., 8, .1)
plt.plot(x, density(x))
plt.show()
You can easily replace gaussian_kde()
by a different kernel density estimate.
Since no one has mentioned pipenv here, I would like to describe my views why everyone should use it for managing python packages.
As @ColonelPanic mentioned there are several issues with the Python Package Index and with pip and virtualenv also.
Pipenv solves most of the issues with pip and provides additional features also.
Pipenv is intended to replace pip and virtualenv, which means pipenv will automatically create a separate virtual environment for every project thus avoiding conflicts between different python versions/package versions for different projects.
If you have worked on python projects before, you would realize these features make managing packages way easier.
check
checks for security vulnerabilities and asserts that PEP 508 requirements are being met by the current environment. (which I think is a great feature especially after this - Malicious packages on PyPi)graph
will show you a dependency graph, of your installed dependencies.You can read more about it here - Pipenv.
You can find the installation documentation here
P.S.: If you liked working with the Python Package requests , you would be pleased to know that pipenv is by the same developer Kenneth Reitz
Anyone can use underscore _ (its Okay)
No one should use hypen - (its Bad practice)
No one should use capital letters inside package names (Bad practice)
NOTE: Here "Bad Practice" is meant for technically you are allowed to use that, but conventionally its not in good manners to write.
Source: Naming a Package(docs.oracle)
$insert = $this->db->insert('email_notification', $data);
$this->session->set_flashdata("msg", "<div class='alert alert-success'> Cafe has been added Successfully.</div>");
//require ("plugins/mailer/PHPMailerAutoload.php");
$mail = new PHPMailer;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
),
);
$message="
Your Account Has beed created successfully by Admin:
Username: ".$this->input->post('username')." <br><br>
Email: ".$this->input->post('sender_email')." <br><br>
Regargs<br>
<div class='background-color:#666;color:#fff;padding:6px;
text-align:center;'>
Bookly Admin.
</div>
";
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true;
$subject = "Hello ".$this->input->post('username');
$mail->SMTDebug=2;
$email = $this->input->post('sender_email'); //this email is user email
$from_label = "Account Creation";
$mail->Username = 'your email'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;
$mail->setFrom($from_label);
$mail->addAddress($email, 'Bookly Admin');
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if($mail->send()){
}
You have to declare your functions before main()
(or declare the function prototypes before main()
)
As it is, the compiler sees my_print (my_string);
in main()
as a function declaration.
Move your functions above main()
in the file, or put:
void my_print (char *);
void my_print2 (char *);
Above main()
in the file.
For files in a directory, you can use things like:
if exist *.csv echo "csv file found"
or
if not exist *.csv goto nofile
or
if (StringA.Equals(StringB, StringComparison.CurrentCultureIgnoreCase)) {
but you need to be sure that StringA is not null. So probably better tu use:
string.Equals(StringA , StringB, StringComparison.CurrentCultureIgnoreCase);
as John suggested
EDIT: corrected the bug
Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly mscorlib
Yes, this technically can go wrong when you execute code on .NET 4.0 instead of .NET 4.5. The attribute was moved from System.Core.dll to mscorlib.dll in .NET 4.5. While that sounds like a rather nasty breaking change in a framework version that is supposed to be 100% compatible, a [TypeForwardedTo] attribute is supposed to make this difference unobservable.
As Murphy would have it, every well intended change like this has at least one failure mode that nobody thought of. This appears to go wrong when ILMerge was used to merge several assemblies into one and that tool was used incorrectly. A good feedback article that describes this breakage is here. It links to a blog post that describes the mistake. It is rather a long article, but if I interpret it correctly then the wrong ILMerge command line option causes this problem:
/targetplatform:"v4,c:\windows\Microsoft.NET\Framework\v4.0.30319"
Which is incorrect. When you install 4.5 on the machine that builds the program then the assemblies in that directory are updated from 4.0 to 4.5 and are no longer suitable to target 4.0. Those assemblies really shouldn't be there anymore but were kept for compat reasons. The proper reference assemblies are the 4.0 reference assemblies, stored elsewhere:
/targetplatform:"v4,C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"
So possible workarounds are to fall back to 4.0 on the build machine, install .NET 4.5 on the target machine and the real fix, to rebuild the project from the provided source code, fixing the ILMerge command.
Do note that this failure mode isn't exclusive to ILMerge, it is just a very common case. Any other scenario where these 4.5 assemblies are used as reference assemblies in a project that targets 4.0 is liable to fail the same way. Judging from other questions, another common failure mode is in build servers that were setup without using a valid VS license. And overlooking that the multi-targeting packs are a free download.
Using the reference assemblies in the c:\program files (x86) subdirectory is a rock hard requirement. Starting at .NET 4.0, already important to avoid accidentally taking a dependency on a class or method that was added in the 4.01, 4.02 and 4.03 releases. But absolutely essential now that 4.5 is released.
Unless it's just a simplified example for the question, my advice is that drop the batch wrapper and schedule PHP directly, more specifically the php-win.exe
program, which won't open unnecessary windows.
Program: c:\program files\php\php-win.exe
Arguments: D:\mydocs\mp\index.php param1 param2
Otherwise, just quote stuff as Andrew points out.
In older versions of Windows, you should be able to put everything in the single "Run" text box (as long as you quote everything that has spaces):
"c:\program files\php\php-win.exe" D:\mydocs\mp\index.php param1 param2
This is the updated answer for WAMP v3.0.6 and up
> UPDATE mysql.user
> SET authentication_string=PASSWORD('MyNewPass')
> WHERE user='root';
> FLUSH PRIVILEGES;
In MySQL version 5.7.x there is no more password field in the mysql table. It was replaced with authentication_string. (This is for the terminal/CLI)
UPDATE mysql.user SET authentication_string=PASSWORD('MyNewPass') WHERE user='root';
FLUSH PRIVILEGES;
(This if for PHPMyAdmin or any Mysql GUI)
The docs give a fair indicator of what's required., however requests
allow us to skip a few steps:
You only need to install the security
package extras (thanks @admdrew for pointing it out)
$ pip install requests[security]
or, install them directly:
$ pip install pyopenssl ndg-httpsclient pyasn1
Requests will then automatically inject pyopenssl
into urllib3
If you're on ubuntu, you may run into trouble installing pyopenssl
, you'll need these dependencies:
$ apt-get install libffi-dev libssl-dev
add #include <iostream>
to the start of io.cpp
too.
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.
from PIL import Image
jpgfile = Image.open("picture.jpg")
print(jpgfile.bits, jpgfile.size, jpgfile.format)
For Xamarin Developers, please use : SupportActionBar.Elevation = 0;
for AppCompatActivity
or ActionBar.Elevation = 0;
for non-compat Activities
The activity in which you want to add listview footer and i have also generate an event on listview footer click.
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list_of_f = (ListView) findViewById(R.id.list_of_f);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.web_view, null); // i have open a webview on the listview footer
RelativeLayout layoutFooter = (RelativeLayout) view.findViewById(R.id.layoutFooter);
list_of_f.addFooterView(view);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg" >
<ImageView
android:id="@+id/dept_nav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/dept_nav" />
<ListView
android:id="@+id/list_of_f"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/dept_nav"
android:layout_margin="5dp"
android:layout_marginTop="10dp"
android:divider="@null"
android:dividerHeight="0dp"
android:listSelector="@android:color/transparent" >
</ListView>
</RelativeLayout>
This is a solution with no deprecated class or method : (Java 8 approved)
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
Important information : Using NoopHostnameVerifier is a security risk
A stored procedure is mainly used to perform certain tasks on a database. For example
I am running PHP version 5.4 on shared hosting and both of these both successfully return the same results:
php_uname('n');
gethostname();
Yes, this is definitely possible. You'll need to have the php function in a separate php file. Here's an example using $.post:
$.post(
'yourphpscript.php', // location of your php script
{ name: "bob", user_id: 1234 }, // any data you want to send to the script
function( data ){ // a function to deal with the returned information
$( 'body ').append( data );
});
And then, in your php script, just echo the html you want. This is a simple example, but a good place to get started:
<?php
echo '<div id="test">Hello, World!</div>';
?>
netstat -ano|grep 443|grep LISTEN
will tell you whether a process is listening on port 443 (you might have to replace LISTEN with a string in your language, though, depending on your system settings).
Web applications require more memory, presumably because you have no choice but to compile into a single assembly. I just converted a large legacy site to a web application and have issues with running out of memory, both at compile time with the error message as below :
Unexpected error writing metadata to file '' --
Not enough storage is available to complete this operation.
error, and at runtime with this error message as below :
Exception information:
Exception type: HttpException
Exception message: Exception of type 'System.OutOfMemoryException' was thrown.
at System.Web.Compilation.BuildManager.ReportTopLevelCompilationException()
My recommendation for converting larger sites on memory-constrained legacy hardware is, to choose the option to revert back to the web site model. Even after an initial success problem might creep up later.
I really don't see what is the big deal with this I mean look if a run my sp which is CALL ps_get_roles();
.
Yes I get back an ugly ass response from DB and stuff. Which is this one:
[
[
RowDataPacket {
id: 1,
role: 'Admin',
created_at: '2019-12-19 16:03:46'
},
RowDataPacket {
id: 2,
role: 'Recruiter',
created_at: '2019-12-19 16:03:46'
},
RowDataPacket {
id: 3,
role: 'Regular',
created_at: '2019-12-19 16:03:46'
}
],
OkPacket {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 35,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
]
it is an array that kind of look like this:
rows[0] = [
RowDataPacket {/* them table rows*/ },
RowDataPacket { },
RowDataPacket { }
];
rows[1] = OkPacket {
/* them props */
}
but if I do an http response
to index [0]
of rows at the client I get:
[
{"id":1,"role":"Admin","created_at":"2019-12-19 16:03:46"},
{"id":2,"role":"Recruiter","created_at":"2019-12-19 16:03:46"},
{"id":3,"role":"Regular","created_at":"2019-12-19 16:03:46"}
]
and I didnt have to do none of yow things
rows[0].map(row => {
return console.log("row: ", {...row});
});
the output gets some like this:
row: { id: 1, role: 'Admin', created_at: '2019-12-19 16:03:46' }
row: { id: 2, role: 'Recruiter', created_at: '2019-12-19 16:03:46' }
row: { id: 3, role: 'Regular', created_at: '2019-12-19 16:03:46' }
So you all is tripping for no reason. Or it also could be the fact that I'm running store procedures instead of regular querys, the response from query and sp is not the same.
I just wanted to add that the problem may be even simpler -
I've been scratching my head for hours with this problem - I have read all the solutions, nothing worked. Then I managed to check the actual file name.
I had "image.jpg.jpg
" rather than "image.jpg
".
If you use $ ls public/..path to image assets../
you can quickly check the file names.
Sounds stupid but I never thought to look at something so simple as file name given the all the technical advice here.
I had the same issue, my problem was that the firewall on the server wasn't open from the current ip address.
Without an ORDER BY
the whole idea of TOP
doesn't make much sense. You need to have a consistent definition of which direction is "up" and which is "down" for the concept of top to be meaningful.
Nonetheless SQL Server allows it but doesn't guarantee a deterministic result.
The UPDATE TOP
syntax in the accepted answer does not support an ORDER BY
clause but it is possible to get deterministic semantics here by using a CTE or derived table to define the desired sort order as below.
;WITH CTE AS
(
SELECT TOP 100 *
FROM T1
ORDER BY F2
)
UPDATE CTE SET F1='foo'
If you want to keep python 3, you can follow these directions to create a python 2.7 environment, called py27.
Then you just need to activate py27:
$ conda activate py27
Then you can install spyder on this environment, e.g.:
$ conda install spyder
Then you can start spyder from the command line or navigate to 2.7 version of spyder.exe below the envs directory (e.g. C:\ProgramData\Anaconda3\envs\py27\Scripts)
useState()
is a React hook. Hooks make possible to use state and mutability inside function components.
While you can't use hooks inside classes you can wrap your class component with a function one and use hooks from it. This is a great tool for migrating components from class to function form. Here is a complete example:
For this example I will use a counter component. This is it:
class Hello extends React.Component {_x000D_
constructor(props) {_x000D_
super(props);_x000D_
this.state = { count: props.count };_x000D_
}_x000D_
_x000D_
inc() {_x000D_
this.setState(prev => ({count: prev.count+1}));_x000D_
}_x000D_
_x000D_
render() {_x000D_
return <button onClick={() => this.inc()}>{this.state.count}</button>_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<div id='root'></div>
_x000D_
It is a simple class component with a count state, and state update is done by methods. This is very common pattern in class components. The first thing is to wrap it with a function component with just the same name, that delegate all its properties to the wrapped component. Also you need to render the wrapped component in the function return. Here it is:
function Hello(props) {_x000D_
class Hello extends React.Component {_x000D_
constructor(props) {_x000D_
super(props);_x000D_
this.state = { count: props.count };_x000D_
}_x000D_
_x000D_
inc() {_x000D_
this.setState(prev => ({count: prev.count+1}));_x000D_
}_x000D_
_x000D_
render() {_x000D_
return <button onClick={() => this.inc()}>{this.state.count}</button>_x000D_
}_x000D_
}_x000D_
return <Hello {...props}/>_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<div id='root'></div>
_x000D_
This is exactly the same component, with the same behavior, same name and same properties. Now lets lift the counting state to the function component. This is how it goes:
function Hello(props) {_x000D_
const [count, setCount] = React.useState(0);_x000D_
class Hello extends React.Component {_x000D_
constructor(props) {_x000D_
super(props);_x000D_
this.state = { count: props.count };_x000D_
}_x000D_
_x000D_
inc() {_x000D_
this.setState(prev => ({count: prev.count+1}));_x000D_
}_x000D_
_x000D_
render() {_x000D_
return <button onClick={() => setCount(count+1)}>{count}</button>_x000D_
}_x000D_
}_x000D_
return <Hello {...props}/>_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js" integrity="sha256-3vo65ZXn5pfsCfGM5H55X+SmwJHBlyNHPwRmWAPgJnM=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js" integrity="sha256-qVsF1ftL3vUq8RFOLwPnKimXOLo72xguDliIxeffHRc=" crossorigin="anonymous"></script>_x000D_
<div id='root'></div>
_x000D_
Note that the method inc
is still there, it wont hurt anybody, in fact is dead code. This is the idea, just keep lifting state up. Once you finished you can remove the class component:
function Hello(props) {_x000D_
const [count, setCount] = React.useState(0);_x000D_
_x000D_
return <button onClick={() => setCount(count+1)}>{count}</button>;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js" integrity="sha256-3vo65ZXn5pfsCfGM5H55X+SmwJHBlyNHPwRmWAPgJnM=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js" integrity="sha256-qVsF1ftL3vUq8RFOLwPnKimXOLo72xguDliIxeffHRc=" crossorigin="anonymous"></script>_x000D_
_x000D_
<div id='root'></div>
_x000D_
While this makes possible to use hooks inside class components, I would not recommend you to do so except if you migrating like I did in this example. Mixing function and class components will make state management a mess. I hope this helps
Best Regards
Check out the documentation on MSDN for the Hashtable class.
Represents a collection of key-and-value pairs that are organized based on the hash code of the key.
Also, keep in mind that this is not thread-safe.
It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:
http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/
I added the snippet below as a tl;dr
#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
case $OPTION in
h)
usage
exit 1
;;
t)
TEST=$OPTARG
;;
r)
SERVER=$OPTARG
;;
p)
PASSWD=$OPTARG
;;
v)
VERBOSE=1
;;
?)
usage
exit
;;
esac
done
if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
usage
exit 1
fi
./script.sh -t test -r server -p password -v
This may be too simplistic of an answer (I am still new here), but what I have done in the past to remedy this situation is figured out the percentage of the screen I would like the image to take up. For example, there is one webpage I am working on where the logo must take up 30% of the screen size to look best. I played around and finally tried this code and it has worked for me thus far:
img {
width:30%;
height:auto;
}
That being said, this will change all of your images to be 30% of the screen size at all times. To get around this issue, simply make this a class and apply it to the image that you desire to be at 30% directly. Here is an example of the code I wrote to accomplish this on the aforementioned site:
the CSS portion:
.logo {
position:absolute;
right:25%;
top:0px;
width:30%;
height:auto;
}
the HTML portion:
<img src="logo_001_002.png" class="logo">
Alternatively, you could place ever image you hope to automatically resize into a div of its own and use the class tag option on each div (creating now class tags whenever needed), but I feel like that would cause a lot of extra work eventually. But, if the site calls for it: the site calls for it.
Hopefully this helps. Have a great day!
I know this is an oldie, but thought I might add some value. For those of us running Server Core outside of a domain (domain members can just run Server Manager remotely to add/remove features/roles), you have to resort to command lines.
Powershell users can type "Install-WindowsFeature Web-Asp-Net45"
That should be equivalent to using server manager.
With that code you load the file in memory (as a big string) and then you read that string line by line.
By using Mid$() and InStr() you actually read the "file" twice but since it's in memory, there is no problem.
I don't know if VB's String has a length limit (probably not) but if the text files are hundreds of megabyte in size it's likely to see a performance drop, due to virtual memory usage.
Other than foreground/background term. Another way to hide running window is via vbscript, if is is still available in your system.
DIM objShell
set objShell=wscript.createObject("wscript.shell")
iReturn=objShell.Run("yourcommand.exe", 0, TRUE)
name it as sth.vbs and call it from bat, put in sheduled task, etc. PersonallyI'll disable vbs with no haste at any Windows system I manage :)
As you read through the examples below, just keep in mind this difference
true === true // true
"string" === true // false
1 === true // false
{} === true // false
But
Boolean("string") === true // true
Boolean(1) === true // true
Boolean({}) === true // true
Assertion passes when the statement passed to expect()
evaluates to true
expect(true).toBe(true) // pass
expect("123" === "123").toBe(true) // pass
In all other cases cases it would fail
expect("string").toBe(true) // fail
expect(1).toBe(true); // fail
expect({}).toBe(true) // fail
Even though all of these statements would evaluate to true
when doing Boolean()
:
So you can think of it as 'strict' comparison
This one does exactly the same type of comparison as .toBe(true)
, but was introduced in Jasmine recently in version 3.5.0
on Sep 20, 2019
toBeTruthy
on the other hand, evaluates the output of the statement into boolean first and then does comparison
expect(false).toBeTruthy() // fail
expect(null).toBeTruthy() // fail
expect(undefined).toBeTruthy() // fail
expect(NaN).toBeTruthy() // fail
expect("").toBeTruthy() // fail
expect(0).toBeTruthy() // fail
And IN ALL OTHER CASES it would pass, for example
expect("string").toBeTruthy() // pass
expect(1).toBeTruthy() // pass
expect({}).toBeTruthy() // pass
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.
public class SwitCase {
public static void main (String[] args){
String hello = JOptionPane.showInputDialog("Input a letter: ");
char hi = hello.charAt(0); //get the first char.
switch(hi){
case 'a': System.out.println("a");
}
}
}
split
returns an Iterator
, which you can convert into a Vec
using collect
: split_line.collect::<Vec<_>>()
. Going through an iterator instead of returning a Vec
directly has several advantages:
split
is lazy. This means that it won't really split the line until you need it. That way it won't waste time splitting the whole string if you only need the first few values: split_line.take(2).collect::<Vec<_>>()
, or even if you need only the first value that can be converted to an integer: split_line.filter_map(|x| x.parse::<i32>().ok()).next()
. This last example won't waste time attempting to process the "23.0" but will stop processing immediately once it finds the "1".split
makes no assumption on the way you want to store the result. You can use a Vec
, but you can also use anything that implements FromIterator<&str>
, for example a LinkedList
or a VecDeque
, or any custom type that implements FromIterator<&str>
.Well, I think the error says that it can't find a nib file named "RootViewController" in your project.
You are writing these lines of code,
self.viewController = [[RootViewController alloc] initWithNibName:@"RootViewController_iPhone.xib" bundle:nil];
self.viewController = [[RootViewController alloc] initWithNibName:@"RootViewController_iPad.xib" bundle:nil];
At the same time you are asking it to load a nib file named "RootviewController"..!! Where is it..? Do you have a xib file named "Rootviewcontroller"..?
Here is a (hopefully) universal patch I developed to fix this problem for BootStrap V3. No special requirements other than plugging in the script.
$(':not(.panel) > [data-toggle="collapse"][data-parent]').click(function() {
var parent = $(this).data('parent');
var items = $('[data-toggle="collapse"][data-parent="' + parent + '"]').not(this);
items.each(function() {
var target = $(this).data('target') || '#' + $(this).prop('href').split('#')[1];
$(target).filter('.in').collapse('hide');
});
});
EDIT: Below is a simplified answer which still meets my needs, and I'm now using a delegated click handler:
$(document.body).on('click', ':not(.panel) > [data-toggle="collapse"][data-parent]', function() {
var parent = $(this).data('parent');
var target = $(this).data('target') || $(this).prop('hash');
$(parent).find('.collapse.in').not(target).collapse('hide');
});
This answer explains how to create a Python 3, Jupyter 1, and ipykernel 5 workflow with Poetry dependency management. Poetry makes creating a virtual environment for Jupyter notebooks easy. I strongly recommend against running python3 commands. Python workflows that install global dependencies set you up for dependency hell.
Here's a summary of the clean, reliable Poetry workflow:
poetry add pandas jupyter ipykernel
poetry shell
jupyter notebook
This blog discusses the workflow in more detail. There are clean Conda workflows as well. Watch out for a lot of the answers in this thread - they'll set you down a path that'll cause a lot of pain & suffering.