If all that you need is details of User, for Spring Version 4.x you can use @AuthenticationPrincipal
and @EnableWebSecurity
tag provided by Spring as shown below.
Security Configuration Class:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
}
Controller method:
@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@AuthenticationPrincipal User user) {
...
}
If searching for an element is important, I'd recommend std::set
instead of std::vector
. Using this:
std::find(vec.begin(), vec.end(), x)
runs in O(n) time, but std::set
has its own find()
member (ie. myset.find(x)
) which runs in O(log n) time - that's much more efficient with large numbers of elements
std::set
also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()...
.
HTML forms support GET and POST. (HTML5 at one point added PUT/DELETE, but those were dropped.)
XMLHttpRequest supports every method, including CHICKEN, though some method names are matched against case-insensitively (methods are case-sensitive per HTTP) and some method names are not supported at all for security reasons (e.g. CONNECT).
Browsers are slowly converging on the rules specified by XMLHttpRequest, but as the other comment pointed out there are still some differences.
This will not work if you try to import the file into EXCEL.
Associate the file extension csv with EXCEL.EXE so you will be able to invoke EXCEL by double-clicking the csv file.
Here I place some text followed by the NewLine Char followed by some more text AND enclosing the whole string with double quotes.
Do not use a CR since EXCEL will place part of the string in the next cell.
""text" + NL + "text""
When you invoke EXCEL, you will see this. You may have to auto size the height to see it all. Where the line breaks will depend on the width of the cell.
2
DATE
Here's the code in Basic
CHR$(34,"2", 10,"DATE", 34)
If you're not too worried in accuracy after days, you can simply do the maths
function timeSince(when) { // this ignores months
var obj = {};
obj._milliseconds = (new Date()).valueOf() - when.valueOf();
obj.milliseconds = obj._milliseconds % 1000;
obj._seconds = (obj._milliseconds - obj.milliseconds) / 1000;
obj.seconds = obj._seconds % 60;
obj._minutes = (obj._seconds - obj.seconds) / 60;
obj.minutes = obj._minutes % 60;
obj._hours = (obj._minutes - obj.minutes) / 60;
obj.hours = obj._hours % 24;
obj._days = (obj._hours - obj.hours) / 24;
obj.days = obj._days % 365;
// finally
obj.years = (obj._days - obj.days) / 365;
return obj;
}
then timeSince(pastDate);
and use the properties as you like.
Otherwise you can use .getUTC*
to calculate it, but note it may be slightly slower to calculate
function timeSince(then) {
var now = new Date(), obj = {};
obj.milliseconds = now.getUTCMilliseconds() - then.getUTCMilliseconds();
obj.seconds = now.getUTCSeconds() - then.getUTCSeconds();
obj.minutes = now.getUTCMinutes() - then.getUTCMinutes();
obj.hours = now.getUTCHours() - then.getUTCHours();
obj.days = now.getUTCDate() - then.getUTCDate();
obj.months = now.getUTCMonth() - then.getUTCMonth();
obj.years = now.getUTCFullYear() - then.getUTCFullYear();
// fix negatives
if (obj.milliseconds < 0) --obj.seconds, obj.milliseconds = (obj.milliseconds + 1000) % 1000;
if (obj.seconds < 0) --obj.minutes, obj.seconds = (obj.seconds + 60) % 60;
if (obj.minutes < 0) --obj.hours, obj.minutes = (obj.minutes + 60) % 60;
if (obj.hours < 0) --obj.days, obj.hours = (obj.hours + 24) % 24;
if (obj.days < 0) { // months have different lengths
--obj.months;
now.setUTCMonth(now.getUTCMonth() + 1);
now.setUTCDate(0);
obj.days = (obj.days + now.getUTCDate()) % now.getUTCDate();
}
if (obj.months < 0) --obj.years, obj.months = (obj.months + 12) % 12;
return obj;
}
A lazy way of doing this if there are alot of tables to be deleted.
Get table using the below
Copy and paste the table names from the result set and paste it after the DROP command.
This is lighter weight than xrange
(and the while loop) since it doesn't even need to create the int
objects. It also works equally well in Python2 and Python3
from itertools import repeat
for i in repeat(None, 10):
do_sth()
There is no datetime dtype to be set for read_csv as csv files can only contain strings, integers and floats.
Setting a dtype to datetime will make pandas interpret the datetime as an object, meaning you will end up with a string.
The pandas.read_csv()
function has a keyword argument called parse_dates
Using this you can on the fly convert strings, floats or integers into datetimes using the default date_parser
(dateutil.parser.parser
)
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = {'col1': 'str', 'col2': 'str', 'col3': 'str', 'col4': 'float'}
parse_dates = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes, parse_dates=parse_dates)
This will cause pandas to read col1
and col2
as strings, which they most likely are ("2016-05-05" etc.) and after having read the string, the date_parser for each column will act upon that string and give back whatever that function returns.
The pandas.read_csv()
function also has a keyword argument called date_parser
Setting this to a lambda function will make that particular function be used for the parsing of the dates.
You have to give it the function, not the execution of the function, thus this is Correct
date_parser = pd.datetools.to_datetime
This is incorrect:
date_parser = pd.datetools.to_datetime()
pd.datetools.to_datetime
has been relocated to date_parser = pd.to_datetime
Thanks @stackoverYC
On Windows 7 I solved this by going into my environment settings (try this link for how) and adding user variables http_proxy
and https_proxy
with my proxy details.
Be aware of that only 32 bit version of PHP is available on the Windows platform.
Then if you for instance shift << or >> more than by 31 bits, results are unexpectable. Usually the original number instead of zeros will be returned, and it can be a really tricky bug.
Of course if you use 64 bit version of PHP (Unix), you should avoid shifting by more than 63 bits. However, for instance, MySQL uses the 64-bit BIGINT, so there should not be any compatibility problems.
UPDATE: From PHP 7 Windows, PHP builds are finally able to use full 64 bit integers: The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except on Windows prior to PHP 7, where it was always 32 bit.
To add button you may use either jQuery libraries or simple Javascript script as shown below:
HTML link or button:
<a href="#" onClick="goclear()" id="button">click event</a>
Javascript:
<script type="text/javascript">
var btn = document.getElementById('button');
function goclear() {
alert("Handler called. Page will redirect to clear.php");
document.location.href = "clear.php";
};
</script>
Use PHP to clear a file content. For instance you can use the fseek($fp, 0); or ftruncate ( resource $file , int $size ) as below:
<?php
//open file to write
$fp = fopen("/tmp/file.txt", "r+");
// clear content to 0 bits
ftruncate($fp, 0);
//close file
fclose($fp);
?>
Redirect PHP - you can use header ( string $string [, bool $replace = true [, int $http_response_code ]] )
<?php
header('Location: getbacktoindex.html');
?>
I hope it's help.
If you want to permit an array of hashes(or an array of objects
from the perspective of JSON)
params.permit(:foo, array: [:key1, :key2])
2 points to notice here:
array
should be the last argument of the permit
method.Unpermitted parameter: array
, which is very difficult to debug in this case.I like putting the inputs inside the labels (added bonus: now you don't need the for
attribute on the label), and put vertical-align: middle
on the input.
label > input[type=radio] {_x000D_
vertical-align: middle;_x000D_
margin-top: -2px;_x000D_
}_x000D_
_x000D_
#d2 { _x000D_
font-size: 30px;_x000D_
}
_x000D_
<div>_x000D_
<label><input type="radio" name="radio" value="1">Good</label>_x000D_
<label><input type="radio" name="radio" value="2">Excellent</label>_x000D_
<div>_x000D_
<br>_x000D_
<div id="d2">_x000D_
<label><input type="radio" name="radio2" value="1">Good</label>_x000D_
<label><input type="radio" name="radio2" value="2">Excellent</label>_x000D_
<div>
_x000D_
(The -2px margin-top
is a matter of taste.)
Another option I really like is using a table. (Hold your pitch forks! It's really nice!) It does mean you need to add the for
attribute to all your labels and id
s to your inputs. I'd recommended this option for labels with long text content, over multiple lines.
<table><tr><td>_x000D_
<input id="radioOption" name="radioOption" type="radio" />_x000D_
</td><td>_x000D_
<label for="radioOption"> _x000D_
Really good option_x000D_
</label>_x000D_
</td></tr></table>
_x000D_
Here are some good sample applications. Below is one possible way.
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName (current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
{
//Ignore the current process
if (process.Id != current.Id)
{
//Make sure that the process is running from the exe file.
if (Assembly.GetExecutingAssembly().Location.
Replace("/", "\\") == current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;
}
if (MainForm.RunningInstance() != null)
{
MessageBox.Show("Duplicate Instance");
//TODO:
//Your application logic for duplicate
//instances would go here.
}
Many other possible ways. See the examples for alternatives.
EDIT 1: Just saw your comment that you have got a console application. That is discussed in the second sample.
You can't really force the optimizer to do anything, but you can guide it.
UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93
If you are using Maven and packaging your Java classes as JAR, then make sure that JAR is up to date. Still assuming that JAR is in your classpath of course.
If Age and Palt are columns in the same Table, you can count(*) all tasks and sum only late ones like this:
select ks,
count(*) tasks,
sum(case when Age > Palt then 1 end) late
from Table
group by ks
For windows, you need to download the latest version of the open SSL binaries at this time is:
openssl-1.0.2k-x64_86-win64.zip
this problem happened to me when I tried to run MongoDB bin in windows 10
source to download: https://indy.fulgan.com/SSL/
This line:
myForm.file.$setValidity("myForm.file.$error.size", false);
Should be
$scope.myForm.file.$setValidity("size", false);
I faced similar problem today. So, here's a simple solution: While doing SSH to the machine, just add Ctrl - Y.
ssh user@ip_address -Y
After login, type firefox &
.
And you are good to go.
You can use a FileOutputStream for this.
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("myFile"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Put data in your baos
baos.writeTo(fos);
} catch(IOException ioe) {
// Handle exception here
ioe.printStackTrace();
} finally {
fos.close();
}
It looks like you're using Python 3.0, in which print has turned into a callable function rather than a statement.
print('Hello world!')
I just right-clicked, and opened with Visual Studio XXXX (in my case 2015). Then save it. Done.
I was using Android Studio to clone the project from GitHub private repository and two-factor authentication (2FA). I created a personal token as made in lzl124631x's answer.
Then I cloned the repo using an url like this: https://YourGitHubUsername:[email protected]/YourRepoPath.git
Use filter
, or if the number of dictionaries in exampleSet
is too high, use ifilter
of the itertools
module. It would return an iterator, instead of filling up your system's memory with the entire list at once:
from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
print elem
in some case you can use annotation @Primary.
@Primary
class USA implements Country {}
This way it will be selected as the default autowire candididate, with no need to autowire-candidate on the other bean.
for mo deatils look at Autowiring two beans implementing same interface - how to set default bean to autowire?
Would it not make sense to use msbuild directly? If you are doing this with every build, then you can add a msbuild task at the end? If you would just like to see if you can’t find another macro value that is not showed on the Visual Studio IDE, you could switch on the msbuild options to diagnostic and that will show you all of the variables that you could use, as well as their current value.
To switch this on in visual studio, go to Tools/Options then scroll down the tree view to the section called Projects and Solutions, expand that and click on Build and Run, at the right their is a drop down that specify the build output verbosity, setting that to diagnostic, will show you what other macro values you could use.
Because I don’t quite know to what level you would like to go, and how complex you want your build to be, this might give you some idea. I have recently been doing build scripts, that even execute SQL code as part of the build. If you would like some more help or even some sample build scripts, let me know, but if it is just a small process you want to run at the end of the build, the perhaps going the full msbuild script is a bit of over kill.
Hope it helps Rihan
Try:
With DependencedIncidents AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
),
lalala AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
)
And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.
The answer above gave me the information needed to resolve this issue. In my case the url was incorrectly starting with ssh:///
To check the url in your git config is correct, open the git config file :-
git config --local -e
Check the url entry. It should NOT have ssh:/// at the start.
Incorrect entry:
url = ssh:///[email protected]:username/repo.git
Correct entry:
url = [email protected]:username/repo.git
If your url is correct, then the next step would be to try the answer above that suggests changing protocol to http.
The strncpy()
function is the safer one: you have to pass the maximum length the destination buffer can accept. Otherwise it could happen that the source string is not correctly 0 terminated, in which case the strcpy()
function could write more characters to destination, corrupting anything which is in the memory after the destination buffer. This is the buffer-overrun problem used in many exploits
Also for POSIX API functions like read()
which does not put the terminating 0 in the buffer, but returns the number of bytes read, you will either manually put the 0, or copy it using strncpy()
.
In your example code, index
is actually not an index, but a count
- it tells how many characters at most to copy from source to destination. If there is no null byte among the first n bytes of source, the string placed in destination will not be null terminated
The extreme and simple cases:
A compiler will produce a binary executable in the target machine's native executable format. This binary file contains all required resources except for system libraries; it's ready to run with no further preparation and processing and it runs like lightning because the code is the native code for the CPU on the target machine.
An interpreter will present the user with a prompt in a loop where he can enter statements or code, and upon hitting RUN
or the equivalent the interpreter will examine, scan, parse and interpretatively execute each line until the program runs to a stopping point or an error. Because each line is treated on its own and the interpreter doesn't "learn" anything from having seen the line before, the effort of converting human-readable language to machine instructions is incurred every time for every line, so it's dog slow. On the bright side, the user can inspect and otherwise interact with his program in all kinds of ways: Changing variables, changing code, running in trace or debug modes... whatever.
With those out of the way, let me explain that life ain't so simple any more. For instance,
In the end, these days, interpreting vs. compiling is a trade-off, with time spent (once) compiling often being rewarded by better runtime performance, but an interpretative environment giving more opportunities for interaction. Compiling vs. interpreting is mostly a matter of how the work of "understanding" the program is divided up between different processes, and the line is a bit blurry these days as languages and products try to offer the best of both worlds.
You can OpenGL without a wrapper and use it natively in C#. Just as Jeff Mc said, you would have to import all the functions you need with DllImport.
What he left out is having to create context before you can use any of the OpenGL functions. It's not hard, but there are few other not-so-intuitive DllImports that need to be done.
I have created an example C# project in VS2012 with almost the bare minimum necessary to get OpenGL running on Windows box. It only paints the window blue, but it should be enough to get you started. The example can be found at http://www.glinos-labs.org/?q=programming-opengl-csharp. Look for the No Wrapper example at the bottom.
By lines I assume you mean rows in the table person
. What you're looking for is:
select p.name
from person p
where p.name LIKE '%A%'; --contains the character 'A'
The above is case sensitive. For a case insensitive search, you can do:
select p.name
from person p
where UPPER(p.name) LIKE '%A%'; --contains the character 'A' or 'a'
For the special character, you can do:
select p.name
from person p
where p.name LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)
The LIKE
operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the %
sign as it means match zero or more characters.
You are adding all defined constraints to self.view
which is wrong, as width and height constraint should be added to your newView
.
Also, as I understand you want to set constant width and height 100:100. In this case you should change your code to:
var constW = NSLayoutConstraint(item: newView,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: 100)
newView.addConstraint(constW)
var constH = NSLayoutConstraint(item: newView,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: 100)
newView.addConstraint(constH)
In vim
:%s/<option value='.\{1,}' >//
or
:%s/<option value='.\+' >//
In vim regular expressions you have to escape the one-or-more symbol, capturing parentheses, the bounded number curly braces and some others.
See :help /magic
to see which special characters need to be escaped (and how to change that).
macgyver offers face detection programs via a simple to use API.
The program below takes a reference to a public image and will return an array of the coordinates and dimensions of any faces detected in the image.
https://askmacgyver.com/explore/program/face-location/5w8J9u4z
An enum is just another class in Java, it should be possible.
More accurately, an enum is an instance of Object: http://docs.oracle.com/javase/6/docs/api/java/lang/Enum.html
So yes, it should work.
I just want to have a button on my website make a PHP file run
<form action="my.php" method="post">
<input type="submit">
</form>
Generally speaking, however, unless you are sending new data to the server to be stored, you would just use a link.
<a href="my.php">run php</a>
(Although you should use link text that describes what happens from the user's point of view, not the servers)
I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately. I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.
This is tricker.
First, you do need to use a form and POST (since you are sending data to be stored).
Then you need to store the data somewhere. This is normally done using a database. Read up on the PDO library for PHP. It is the standard way to interact with databases.
Then you need to pull the data back out again. The simplest approach here is to use the query string to pass the primary key for the database row with the entry you wish to display.
<a href="showBlogEntry.php?entry_id=123">...</a>
Make sure you also read up on SQL injection and XSS.
This is the code that works for me to create a sticky thead on a table with a scrollable tbody:
table ,tr td{
border:1px solid red
}
tbody {
display:block;
height:50px;
overflow:auto;
}
thead, tbody tr {
display:table;
width:100%;
table-layout:fixed;/* even columns width , fix width of table too*/
}
thead {
width: calc( 100% - 1em )/* scrollbar is average 1em/16px width, remove it from thead width */
}
table {
width:400px;
}
This is how I am doing this in swift.
extension String {
func encodeURIComponent() -> String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
}
func decodeURIComponent() -> String {
return self.componentsSeparatedByString("+").joinWithSeparator(" ").stringByRemovingPercentEncoding!
}
}
Load names with tf.train.match_filenames_once get the number of files to iterate over with tf.size open session and enjoy ;-)
import tensorflow as tf
import numpy as np
import matplotlib;
from PIL import Image
matplotlib.use('Agg')
import matplotlib.pyplot as plt
filenames = tf.train.match_filenames_once('./images/*.jpg')
count_num_files = tf.size(filenames)
filename_queue = tf.train.string_input_producer(filenames)
reader=tf.WholeFileReader()
key,value=reader.read(filename_queue)
img = tf.image.decode_jpeg(value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
num_files = sess.run(count_num_files)
for i in range(num_files):
image=img.eval()
print(image.shape)
Image.fromarray(np.asarray(image)).save('te.jpeg')
Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime
class, which along with it's related classes, really should be in any PHP developer's toolkit.
// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it.
$datetime = DateTime::createFromFormat('g:i:s', $selectedTime);
$datetime->modify('+15 minutes');
echo $datetime->format('g:i:s');
Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:
!g:i:s
12-hour format without leading zeroes on hour
!G:i:s
12-hour format with leading zeroes
Note the !
item in format. This would set date component to first day in Linux epoch (1-1-1970)
Just style the border of the rows:
?table tr {
border-bottom: 1px solid black;
}?
table tr:last-child {
border-bottom: none;
}
Here is a fiddle.
Edited as mentioned by @pkyeck. The second style avoids the line under the last row. Maybe you are looking for this.
FYI you can sometimes use SYSTEM or Trustedinstaller to kill tasks ;)
google quickkill_3_0.bat
sc config TrustedInstaller binPath= "cmd /c TASKKILL /F /IM notepad.exe
sc start "TrustedInstaller"
I ran into this same issue and realized that, since I am using spring boot, all I needed to do to resolve the issue was to add the following dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
If mapping is proper then you can undo/checkin your changes, if you really want to change folder name.
Alternatively if you want to remove mapping then in Visual Studio go to File-> Source Control-> Advanced-> Workspaces-> Edit
Now you can click on appropriate path and remove mapping.
Something like:
$qb = $entityManager->createQueryBuilder();
$qb->select('count(account.id)');
$qb->from('ZaysoCoreBundle:Account','account');
$count = $qb->getQuery()->getSingleScalarResult();
Some folks feel that expressions are somehow better than just using straight DQL. One even went so far as to edit a four year old answer. I rolled his edit back. Go figure.
As you know the display
property cannot be animated BUT just by having it in your CSS it overrides the visibility
and opacity
transitions.
The solution...just removed the display
properties.
nav.main ul ul {_x000D_
position: absolute;_x000D_
list-style: none;_x000D_
opacity: 0;_x000D_
visibility: hidden;_x000D_
padding: 10px;_x000D_
background-color: rgba(92, 91, 87, 0.9);_x000D_
-webkit-transition: opacity 600ms, visibility 600ms;_x000D_
transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
nav.main ul li:hover ul {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
}
_x000D_
<nav class="main">_x000D_
<ul>_x000D_
<li>_x000D_
<a href="">Lorem</a>_x000D_
<ul>_x000D_
<li><a href="">Ipsum</a>_x000D_
</li>_x000D_
<li><a href="">Dolor</a>_x000D_
</li>_x000D_
<li><a href="">Sit</a>_x000D_
</li>_x000D_
<li><a href="">Amet</a>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>
_x000D_
Try:
ORDER BY x_field='F', x_field='P', x_field='A', x_field='I'
You were on the right track, but by putting x_field only on the F value, the other 3 were treated as constants and not compared against anything in the dataset.
You can use JustifiedTextView for Android project in github. this is a custom view that simulate justified text for you. It support Android 2.0+ and right to left languages.
I have done this like this:
Load the font:
- (void)loadFont{
// Get the path to our custom font and create a data provider.
NSString *fontPath = [[NSBundle mainBundle] pathForResource:@"mycustomfont" ofType:@"ttf"];
CGDataProviderRef fontDataProvider = CGDataProviderCreateWithFilename([fontPath UTF8String]);
// Create the font with the data provider, then release the data provider.
customFont = CGFontCreateWithDataProvider(fontDataProvider);
CGDataProviderRelease(fontDataProvider);
}
Now, in your drawRect:
, do something like this:
-(void)drawRect:(CGRect)rect{
[super drawRect:rect];
// Get the context.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
// Set the customFont to be the font used to draw.
CGContextSetFont(context, customFont);
// Set how the context draws the font, what color, how big.
CGContextSetTextDrawingMode(context, kCGTextFillStroke);
CGContextSetFillColorWithColor(context, self.fontColor.CGColor);
UIColor * strokeColor = [UIColor blackColor];
CGContextSetStrokeColorWithColor(context, strokeColor.CGColor);
CGContextSetFontSize(context, 48.0f);
// Create an array of Glyph's the size of text that will be drawn.
CGGlyph textToPrint[[self.theText length]];
// Loop through the entire length of the text.
for (int i = 0; i < [self.theText length]; ++i) {
// Store each letter in a Glyph and subtract the MagicNumber to get appropriate value.
textToPrint[i] = [[self.theText uppercaseString] characterAtIndex:i] + 3 - 32;
}
CGAffineTransform textTransform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
CGContextSetTextMatrix(context, textTransform);
CGContextShowGlyphsAtPoint(context, 20, 50, textToPrint, [self.theText length]);
}
Basically you have to do some brute force looping through the text and futzing about with the magic number to find your offset (here, see me using 29) in the font, but it works.
Also, you have to make sure the font is legally embeddable. Most aren't and there are lawyers who specialize in this sort of thing, so be warned.
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
Another way to do this is to add the new characters to the string as follows:
Dim str As String
str = ""
To append text to your string this way:
str = str & "and this is more text"
much easier way!
devtools::install_github("yikeshu0611/onetree") #install onetree package
library(onetree)
widedata=reshape_toWide(data = dat1,id = "name",j = "numbers",value.var.prefix = "value")
widedata
name value1 value2 value3 value4
firstName 0.3407997 -0.7033403 -0.3795377 -0.7460474
secondName -0.8981073 -0.3347941 -0.5013782 -0.1745357
if you want to go back from wide to long, only change Wide to Long, and no changes in objects.
reshape_toLong(data = widedata,id = "name",j = "numbers",value.var.prefix = "value")
name numbers value
firstName 1 0.3407997
secondName 1 -0.8981073
firstName 2 -0.7033403
secondName 2 -0.3347941
firstName 3 -0.3795377
secondName 3 -0.5013782
firstName 4 -0.7460474
secondName 4 -0.1745357
Don't use a symbolic Link to move the docker folder to /mnt (for example). This may cause in trouble with the docker rm command.
Better use the -g Option for docker. On Ubuntu you can set it permanently in /etc/default/docker.io. Enhance or replace the DOCKER_OPTS Line.
Here an example: `DOCKER_OPTS="-g /mnt/somewhere/else/docker/"
For a similar situation I used this PKCS #5: Password-Based Cryptography Standard from RSA laboratories. You can avoid storing password, by substituting it with something that can be generated only from the password (in one sentence). There are some JavaScript implementations.
Just for clarification: setRequestProperty("User-Agent", "Mozilla ...")
now works just fine and doesn't append java/xx
at the end! At least with Java 1.6.30 and newer.
I listened on my machine with netcat(a port listener):
$ nc -l -p 8080
It simply listens on the port, so you see anything which gets requested, like raw http-headers.
And got the following http-headers without setRequestProperty:
GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
And WITH setRequestProperty:
GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
As you can see the user agent was properly set.
Full example:
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class TestUrlOpener {
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:8080/foobar");
URLConnection hc = url.openConnection();
hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
System.out.println(hc.getContentType());
}
}
See excerpt from official documentation for containment
option:
containment
Default:
false
Constrains dragging to within the bounds of the specified element or region.
Multiple types supported:
- Selector: The draggable element will be contained to the bounding box of the first element found by the selector. If no element is found, no containment will be set.
- Element: The draggable element will be contained to the bounding box of this element.
- String: Possible values:
"parent"
,"document"
,"window"
.- Array: An array defining a bounding box in the form
[ x1, y1, x2, y2 ]
.Code examples:
Initialize the draggable with thecontainment
option specified:$( ".selector" ).draggable({ containment: "parent" });
Get or set the
containment
option, after initialization:// Getter var containment = $( ".selector" ).draggable( "option", "containment" ); // Setter $( ".selector" ).draggable( "option", "containment", "parent" );
Remove all the containers
docker ps -q -a | xargs docker rm
Force remove all the Docker images
docker rmi -f $(docker images -f dangling=true -q)
If your array has a natural order use binary search.
Use binary search.
Binary search has O(log n)
access time.
Here are the steps on how to use binary search,
bsearch
to find elements or indicesCode example
# assume array is sorted by name!
array.bsearch { |each| "Jamie" <=> each.name } # returns element
(0..array.size).bsearch { |n| "Jamie" <=> array[n].name } # returns index
According to protocol documentation there are at least three options website designers can use to inform sitemap.xml location to search engines:
So, unless they have chosen to publish the sitemap location on their robots.txt file, you cannot really know where they have put their sitemap.xml files.
One simple approach would be to use the !important
modifier in css, but this can be overridden in the same way from users.
Maybe a solution can be achieved with jquery by traversing the entire DOM to find your (re)defined classes and removing / forcing css styles.
Check out the apache config files. For Debian/Ubuntu theyre in /etc/apache2/sites-available/
for RedHat/CentOS/etc they're in /etc/httpd/conf.d/
. If you've just installed it, the file in there is probably named default
.
Make sure that the config file in there is pointing to the correct folder and then make sure your scripts are located there.
The line you're looking for in those files is DocumentRoot /path/to/directory
.
For a blank install, your php files most likely needs to be in /var/www/
.
What you'll also need to do is find your php.ini file, probably located at /etc/php5/apache2/php.ini
or /etc/php.ini
and find the entry for display_errors
and switch it to On
.
It can be Cisco AnyConnect. Check if /Library/LaunchDaemons/com.cisco.anyconnect.vpnagentd.plist exists. Then unload it with launchctl and delete from /Library/LaunchDaemons
In mechanical terms a COMMIT makes a transaction. That is, a transaction is all the activity (one or more DML statements) which occurs between two COMMIT statements (or ROLLBACK).
In Oracle a DDL statement is a transaction in its own right simply because an implicit COMMIT is issued before the statement is executed and again afterwards. TRUNCATE is a DDL command so it doesn't need an explicit commit because calling it executes an implicit commit.
From a system design perspective a transaction is a business unit of work. It might consist of a single DML statement or several of them. It doesn't matter: only full transactions require COMMIT. It literally does not make sense to issue a COMMIT unless or until we have completed a whole business unit of work.
This is a key concept. COMMITs don't just release locks. In Oracle they also release latches, such as the Interested Transaction List. This has an impact because of Oracle's read consistency model. Exceptions such as ORA-01555: SNAPSHOT TOO OLD
or ORA-01002: FETCH OUT OF SEQUENCE
occur because of inappropriate commits. Consequently, it is crucial for our transactions to hang onto locks for as long as they need them.
Apart from the question whether class decorators are the right solution to your problem:
In Python 2.6 and higher, there are class decorators with the @-syntax, so you can write:
@addID
class Foo:
pass
In older versions, you can do it another way:
class Foo:
pass
Foo = addID(Foo)
Note however that this works the same as for function decorators, and that the decorator should return the new (or modified original) class, which is not what you're doing in the example. The addID decorator would look like this:
def addID(original_class):
orig_init = original_class.__init__
# Make copy of original __init__, so we can call it without recursion
def __init__(self, id, *args, **kws):
self.__id = id
self.getId = getId
orig_init(self, *args, **kws) # Call the original __init__
original_class.__init__ = __init__ # Set the class' __init__ to the new one
return original_class
You could then use the appropriate syntax for your Python version as described above.
But I agree with others that inheritance is better suited if you want to override __init__
.
Instead of comparing the dates directly, compare the getTime() value of the date. The getTime() function returns the number of milliseconds since Jan 1, 1970 as an integer-- should be trivial to determine if one integer falls between two other integers.
Something like
if((check.getTime() <= to.getTime() && check.getTime() >= from.getTime())) alert("date contained");
Go through project properties -> Reference Paths
Then add folder with DLL's
On Linux with Inkscape 1.0 to convert from svg to png need to use
inkscape -w 1024 -h 1024 input.svg --export-file output.png
not
inkscape -w 1024 -h 1024 input.svg --export-filename output.png
In order to calculate the difference you have to put the +
operator,
that way typescript
converts the dates to numbers.
+new Date()- +new Date("2013-02-20T12:01:04.753Z")
From there you can make a formula to convert the difference to minutes
or hours
.
Can I see your User class? This is just using restrictions below. I don't see why Restrictions would be really any different than Examples (I think null fields get ignored by default in examples though).
getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Restrictions.eq("city", "TEST")))
.setResultTransformer(Transformers.aliasToBean(User.class))
.list();
I've never used the alaistToBean, but I just read about it. You could also just loop over the results..
List<Object> rows = criteria.list();
for(Object r: rows){
Object[] row = (Object[]) r;
Type t = ((<Type>) row[0]);
}
If you have to you can manually populate User yourself that way.
Its sort of hard to look into the issue without some more information to diagnose the issue.
Private Sub CommandButton1_Click()
Workbooks("Textfile_Receiving").Sheets("menu").Range("g1").Value = PROV.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g2").Value = MUN.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g3").Value = CAT.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g4").Value = Label5.Caption
Me.Hide
Run "filename"
End Sub
Private Sub MUN_Change()
Dim r As Integer
r = 2
While Range("m" & CStr(r)).Value <> ""
If Range("m" & CStr(r)).Value = MUN.Text Then
Label5.Caption = Range("n" & CStr(r)).Value
End If
r = r + 1
Wend
End Sub
Private Sub PROV_Change()
If PROV.Text = "LAGUNA" Then
MUN.Text = ""
MUN.RowSource = "Menu!M26:M56"
ElseIf PROV.Text = "CAVITE" Then
MUN.Text = ""
MUN.RowSource = "Menu!M2:M25"
ElseIf PROV.Text = "QUEZON" Then
MUN.Text = ""
MUN.RowSource = "Menu!M57:M97"
End If
End Sub
Plugin DebugKit for cake will do the job as well. https://github.com/cakephp/debug_kit
If you look at the standard libraries the pattern generally is my_function, but every person does seem to have their own way :-/
It's used for raising errors.
if something:
raise Exception('My error!')
Some examples here
$ git push origin develop:master
or, more generally
$ git push <remote> <local branch name>:<remote branch to push into>
NITZ is a form of NTP and is sent to the mobile device over Layer 3 or NAS layers. Commonly this message is seen as GMM Info and contains the following informaiton:
Certain carriers dont support this and some support it and have it setup incorrectly.
LAYER 3 SIGNALING MESSAGE
Time: 9:38:49.800
GMM INFORMATION 3GPP TS 24.008 ver 12.12.0 Rel 12 (9.4.19)
M Protocol Discriminator (hex data: 8)
(0x8) Mobility Management message for GPRS services
M Skip Indicator (hex data: 0) Value: 0 M Message Type (hex data: 21) Message number: 33
O Network time zone (hex data: 4680) Time Zone value: GMT+2:00 O Universal time and time zone (hex data: 47716070 70831580) Year: 17 Month: 06 Day: 07 Hour: 07 Minute :38 Second: 51 Time zone value: GMT+2:00 O Network Daylight Saving Time (hex data: 490100) Daylight Saving Time value: No adjustment
Layer 3 data: 08 21 46 80 47 71 60 70 70 83 15 80 49 01 00
You simply need to add that line legend: { display: false }
(fiddle: https://jsfiddle.net/ya3ya6/7hfkdnrg/2/ )
Html:
<textarea id='tbMain' ></textarea>
<a id='btnOpen' href='#' >Open</a>
Js:
document.getElementById('btnOpen').onclick = function(){
openFile(function(txt){
document.getElementById('tbMain').value = txt;
});
}
function openFile(callBack){
var element = document.createElement('input');
element.setAttribute('type', "file");
element.setAttribute('id', "btnOpenFile");
element.onchange = function(){
readText(this,callBack);
document.body.removeChild(this);
}
element.style.display = 'none';
document.body.appendChild(element);
element.click();
}
function readText(filePath,callBack) {
var reader;
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
callBack(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
You can try out
ThisWorkbook.Save
ThisWorkbook.Saved = True
Application.Quit
The best way is to use menu mnemonics, i.e. to have menu entries in your main form that get assigned the keyboard shortcut you want. Then everything else is handled internally and all you have to do is to implement the appropriate action that gets executed in the Click
event handler of that menu entry.
$_SERVER['HTTP_REFERER'];
But if you run a file (that contains the above code) by directly hitting the URL in the browser then you get the following error.
Notice: Undefined index: HTTP_REFERER
Using the C++ API, the function name has slightly changed and it writes now:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);
The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.
OpenCV 3
Starting with OpenCV 3.0, there is yet another convention.
Conversion codes are embedded in the namespace cv::
and are prefixed with COLOR
.
So, the example becomes then:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);
As far as I have seen, the included file path hasn't changed (this is not a typo).
Yes it is, there have to be boolean expresion after IF. Here you have a direct link. I hope it helps. GL!
All above answers are very relevant, but if someone still unable to reset the userdefaults for deleted app, then you can reset the content settings of you simulator, and it will work.
Use random.choice()
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
For cryptographically secure random choices (e.g. for generating a passphrase from a wordlist) use secrets.choice()
import secrets
foo = ['battery', 'correct', 'horse', 'staple']
print(secrets.choice(foo))
secrets
is new in Python 3.6, on older versions of Python you can use the random.SystemRandom
class:
import random
secure_random = random.SystemRandom()
print(secure_random.choice(foo))
Yes.
Add DisableCacheViewer Registry Key
Create a new dword key under HKLM\Software\Microsoft\Fusion\ with the name DisableCacheViewer and set it’s [DWORD] value to 1.
Go back to Windows Explorer to the assembly folder and it will be the normal file system view.
log4j2 has a very flexible configuration system (which IMHO is more a distraction than a help), you can even use JSON. See https://logging.apache.org/log4j/2.x/manual/configuration.html for a reference.
Personally, I just recently started using log4j2, but I'm tending toward the "strict XML" configuration (that is, using attributes instead of element names), which can be schema-validated.
Here is my simple example using autoconfiguration and strict mode, using a "Property" for setting the filename:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
<Properties>
<Property name="filename">log/CelsiusConverter.log</Property>
</Properties>
<Appenders>
<Appender type="Console" name="Console">
<Layout type="PatternLayout" pattern="%d %p [%t] %m%n" />
</Appender>
<Appender type="Console" name="FLOW">
<Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n" />
</Appender>
<Appender type="File" name="File" fileName="${filename}">
<Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
</Appender>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="File" />
<AppenderRef ref="Console" />
<!-- Use FLOW to trace down exact method sending the msg -->
<!-- <AppenderRef ref="FLOW" /> -->
</Root>
</Loggers>
</Configuration>
The response itself seems to have the size of the records. You can use that to check if records exist. Something like:
if($response->size > 0){
$role_arr = getRole($response->records);
}
Render Line Endings is a VS Code extension that is still actively maintained (as of Apr 2020):
https://marketplace.visualstudio.com/items?itemName=medo64.render-crlf
https://github.com/medo64/render-crlf/
It can be configured like this:
{
"editor.renderWhitespace": "all",
"code-eol.newlineCharacter": "¬",
"code-eol.returnCharacter" : "¤",
"code-eol.crlfCharacter" : "¤¬",
}
and looks like this:
For swift 3.0 You can also change gesture long press time duration
label.isUserInteractionEnabled = true
let longPress:UILongPressGestureRecognizer = UILongPressGestureRecognizer.init(target: self, action: #selector(userDragged(gesture:)))
longPress.minimumPressDuration = 0.2
label.addGestureRecognizer(longPress)
OK so I think i know the issue you're having.
Basically, because Composer can't see the migration files you are creating, you are having to run the dump-autoload command which won't download anything new, but looks for all of the classes it needs to include again. It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php), and this is why your migration is working after you run that command.
How to fix it (possibly) You need to add some extra information to your composer.json file.
"autoload": {
"classmap": [
"PATH TO YOUR MIGRATIONS FOLDER"
],
}
You need to add the path to your migrations folder to the classmap array. Then run the following three commands...
php artisan clear-compiled
composer dump-autoload
php artisan optimize
This will clear the current compiled files, update the classes it needs and then write them back out so you don't have to do it again.
Ideally, you execute composer dump-autoload -o
, for a faster load of your webpages. The only reason it is not default, is because it takes a bit longer to generate (but is only slightly noticable).
Hope you can manage to get this sorted, as its very annoying indeed :(
There is a much easier way to do without adding the CSS files and all the other methods suggested. But you have to do it every time you start the Jupiter notebook.
Go to inspect in your browser and click on the element selection icon and then click on the box. And at the bottom of the page, you will be seeing the styling option for CSS where you can easily change the font-size.
I also faced it and encorrected it like below successfully.
File > Settings > Build, Execution, Deployment > Gradle > Use local gradle distribution
Set the home path as : C:/Program Files/Android/Android Studio/gradle/gradle-version
You may need to upgrade your gradle version.
You can use a sealed abstract class instead of the enumeration, for example:
sealed abstract class Constraint(val name: String, val verifier: Int => Boolean)
case object NotTooBig extends Constraint("NotTooBig", (_ < 1000))
case object NonZero extends Constraint("NonZero", (_ != 0))
case class NotEquals(x: Int) extends Constraint("NotEquals " + x, (_ != x))
object Main {
def eval(ctrs: Seq[Constraint])(x: Int): Boolean =
(true /: ctrs){ case (accum, ctr) => accum && ctr.verifier(x) }
def main(args: Array[String]) {
val ctrs = NotTooBig :: NotEquals(5) :: Nil
val evaluate = eval(ctrs) _
println(evaluate(3000))
println(evaluate(3))
println(evaluate(5))
}
}
When numbers, dates and times are formatted into strings or parsed from strings a culture is used to determine how it is done. E.g. in the dominant en-US
culture you have these string representations:
In my culture (da-DK
) the values have this string representation:
In the Windows operating system the user may even customize how numbers and date/times are formatted and may also choose another culture than the culture of his operating system. The formatting used is the choice of the user which is how it should be.
So when you format a value to be displayed to the user using for instance ToString
or String.Format
or parsed from a string using DateTime.Parse
or Decimal.Parse
the default is to use the CultureInfo.CurrentCulture
. This allows the user to control the formatting.
However, a lot of string formatting and parsing is actually not strings exchanged between the application and the user but between the application and some data format (e.g. an XML or CSV file). In that case you don't want to use CultureInfo.CurrentCulture
because if formatting and parsing is done with different cultures it can break. In that case you want to use CultureInfo.InvariantCulture
(which is based on the en-US
culture). This ensures that the values can roundtrip without problems.
The reason that ReSharper gives you the warning is that some application writers are unaware of this distinction which may lead to unintended results but they never discover this because their CultureInfo.CurrentCulture
is en-US
which has the same behavior as CultureInfo.InvariantCulture
. However, as soon as the application is used in another culture where there is a chance of using one culture for formatting and another for parsing the application may break.
So to sum it up:
CultureInfo.CurrentCulture
(the default) if you are formatting or parsing a user string.CultureInfo.InvariantCulture
if you are formatting or parsing a string that should be parseable by a piece of software.Use the synchronisation context if you want to send a result to the UI thread. I needed to change the thread priority so I changed from using thread pool threads (commented out code) and created a new thread of my own. I was still able to use the synchronisation context to return whether the database cancel succeeded or not.
#region SyncContextCancel
private SynchronizationContext _syncContextCancel;
/// <summary>
/// Gets the synchronization context used for UI-related operations.
/// </summary>
/// <value>The synchronization context.</value>
protected SynchronizationContext SyncContextCancel
{
get { return _syncContextCancel; }
}
#endregion //SyncContextCancel
public void CancelCurrentDbCommand()
{
_syncContextCancel = SynchronizationContext.Current;
//ThreadPool.QueueUserWorkItem(CancelWork, null);
Thread worker = new Thread(new ThreadStart(CancelWork));
worker.Priority = ThreadPriority.Highest;
worker.Start();
}
SQLiteConnection _connection;
private void CancelWork()//object state
{
bool success = false;
try
{
if (_connection != null)
{
log.Debug("call cancel");
_connection.Cancel();
log.Debug("cancel complete");
_connection.Close();
log.Debug("close complete");
success = true;
log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());
}
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
}
SyncContextCancel.Send(CancelCompleted, new object[] { success });
}
public void CancelCompleted(object state)
{
object[] args = (object[])state;
bool success = (bool)args[0];
if (success)
{
log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());
}
}
I use MVVM, so I created some attached properties of my own, using Thomas's as a reference. It does sorting on one column at a time when you click on the header, toggling between Ascending and Descending. It sorts from the very beginning using the first column. And it shows Win7/8 style glyphs.
Normally, all you have to do is set the main property to true (but you have to explicitly declare the GridViewColumnHeaders):
<Window xmlns:local="clr-namespace:MyProjectNamespace">
<Grid>
<ListView local:App.EnableGridViewSort="True" ItemsSource="{Binding LVItems}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Property1}">
<GridViewColumnHeader Content="Prop 1" />
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Property2}">
<GridViewColumnHeader Content="Prop 2" />
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
<Window>
If you want to sort on a different property than the display, than you have to declare that:
<GridViewColumn DisplayMemberBinding="{Binding Property3}"
local:App.GridViewSortPropertyName="Property4">
<GridViewColumnHeader Content="Prop 3" />
</GridViewColumn>
Here's the code for the attached properties, I like to be lazy and put them in the provided App.xaml.cs:
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data.
using System.Windows.Media;
using System.Windows.Media.Media3D;
namespace MyProjectNamespace
{
public partial class App : Application
{
#region GridViewSort
public static DependencyProperty GridViewSortPropertyNameProperty =
DependencyProperty.RegisterAttached(
"GridViewSortPropertyName",
typeof(string),
typeof(App),
new UIPropertyMetadata(null)
);
public static string GetGridViewSortPropertyName(GridViewColumn gvc)
{
return (string)gvc.GetValue(GridViewSortPropertyNameProperty);
}
public static void SetGridViewSortPropertyName(GridViewColumn gvc, string n)
{
gvc.SetValue(GridViewSortPropertyNameProperty, n);
}
public static DependencyProperty CurrentSortColumnProperty =
DependencyProperty.RegisterAttached(
"CurrentSortColumn",
typeof(GridViewColumn),
typeof(App),
new UIPropertyMetadata(
null,
new PropertyChangedCallback(CurrentSortColumnChanged)
)
);
public static GridViewColumn GetCurrentSortColumn(GridView gv)
{
return (GridViewColumn)gv.GetValue(CurrentSortColumnProperty);
}
public static void SetCurrentSortColumn(GridView gv, GridViewColumn value)
{
gv.SetValue(CurrentSortColumnProperty, value);
}
public static void CurrentSortColumnChanged(
object sender, DependencyPropertyChangedEventArgs e)
{
GridViewColumn gvcOld = e.OldValue as GridViewColumn;
if (gvcOld != null)
{
CurrentSortColumnSetGlyph(gvcOld, null);
}
}
public static void CurrentSortColumnSetGlyph(GridViewColumn gvc, ListView lv)
{
ListSortDirection lsd;
Brush brush;
if (lv == null)
{
lsd = ListSortDirection.Ascending;
brush = Brushes.Transparent;
}
else
{
SortDescriptionCollection sdc = lv.Items.SortDescriptions;
if (sdc == null || sdc.Count < 1) return;
lsd = sdc[0].Direction;
brush = Brushes.Gray;
}
FrameworkElementFactory fefGlyph =
new FrameworkElementFactory(typeof(Path));
fefGlyph.Name = "arrow";
fefGlyph.SetValue(Path.StrokeThicknessProperty, 1.0);
fefGlyph.SetValue(Path.FillProperty, brush);
fefGlyph.SetValue(StackPanel.HorizontalAlignmentProperty,
HorizontalAlignment.Center);
int s = 4;
if (lsd == ListSortDirection.Ascending)
{
PathFigure pf = new PathFigure();
pf.IsClosed = true;
pf.StartPoint = new Point(0, s);
pf.Segments.Add(new LineSegment(new Point(s * 2, s), false));
pf.Segments.Add(new LineSegment(new Point(s, 0), false));
PathGeometry pg = new PathGeometry();
pg.Figures.Add(pf);
fefGlyph.SetValue(Path.DataProperty, pg);
}
else
{
PathFigure pf = new PathFigure();
pf.IsClosed = true;
pf.StartPoint = new Point(0, 0);
pf.Segments.Add(new LineSegment(new Point(s, s), false));
pf.Segments.Add(new LineSegment(new Point(s * 2, 0), false));
PathGeometry pg = new PathGeometry();
pg.Figures.Add(pf);
fefGlyph.SetValue(Path.DataProperty, pg);
}
FrameworkElementFactory fefTextBlock =
new FrameworkElementFactory(typeof(TextBlock));
fefTextBlock.SetValue(TextBlock.HorizontalAlignmentProperty,
HorizontalAlignment.Center);
fefTextBlock.SetValue(TextBlock.TextProperty, new Binding());
FrameworkElementFactory fefDockPanel =
new FrameworkElementFactory(typeof(StackPanel));
fefDockPanel.SetValue(StackPanel.OrientationProperty,
Orientation.Vertical);
fefDockPanel.AppendChild(fefGlyph);
fefDockPanel.AppendChild(fefTextBlock);
DataTemplate dt = new DataTemplate(typeof(GridViewColumn));
dt.VisualTree = fefDockPanel;
gvc.HeaderTemplate = dt;
}
public static DependencyProperty EnableGridViewSortProperty =
DependencyProperty.RegisterAttached(
"EnableGridViewSort",
typeof(bool),
typeof(App),
new UIPropertyMetadata(
false,
new PropertyChangedCallback(EnableGridViewSortChanged)
)
);
public static bool GetEnableGridViewSort(ListView lv)
{
return (bool)lv.GetValue(EnableGridViewSortProperty);
}
public static void SetEnableGridViewSort(ListView lv, bool value)
{
lv.SetValue(EnableGridViewSortProperty, value);
}
public static void EnableGridViewSortChanged(
object sender, DependencyPropertyChangedEventArgs e)
{
ListView lv = sender as ListView;
if (lv == null) return;
if (!(e.NewValue is bool)) return;
bool enableGridViewSort = (bool)e.NewValue;
if (enableGridViewSort)
{
lv.AddHandler(
GridViewColumnHeader.ClickEvent,
new RoutedEventHandler(EnableGridViewSortGVHClicked)
);
if (lv.View == null)
{
lv.Loaded += new RoutedEventHandler(EnableGridViewSortLVLoaded);
}
else
{
EnableGridViewSortLVInitialize(lv);
}
}
else
{
lv.RemoveHandler(
GridViewColumnHeader.ClickEvent,
new RoutedEventHandler(EnableGridViewSortGVHClicked)
);
}
}
public static void EnableGridViewSortLVLoaded(object sender, RoutedEventArgs e)
{
ListView lv = e.Source as ListView;
EnableGridViewSortLVInitialize(lv);
lv.Loaded -= new RoutedEventHandler(EnableGridViewSortLVLoaded);
}
public static void EnableGridViewSortLVInitialize(ListView lv)
{
GridView gv = lv.View as GridView;
if (gv == null) return;
bool first = true;
foreach (GridViewColumn gvc in gv.Columns)
{
if (first)
{
EnableGridViewSortApplySort(lv, gv, gvc);
first = false;
}
else
{
CurrentSortColumnSetGlyph(gvc, null);
}
}
}
public static void EnableGridViewSortGVHClicked(
object sender, RoutedEventArgs e)
{
GridViewColumnHeader gvch = e.OriginalSource as GridViewColumnHeader;
if (gvch == null) return;
GridViewColumn gvc = gvch.Column;
if(gvc == null) return;
ListView lv = VisualUpwardSearch<ListView>(gvch);
if (lv == null) return;
GridView gv = lv.View as GridView;
if (gv == null) return;
EnableGridViewSortApplySort(lv, gv, gvc);
}
public static void EnableGridViewSortApplySort(
ListView lv, GridView gv, GridViewColumn gvc)
{
bool isEnabled = GetEnableGridViewSort(lv);
if (!isEnabled) return;
string propertyName = GetGridViewSortPropertyName(gvc);
if (string.IsNullOrEmpty(propertyName))
{
Binding b = gvc.DisplayMemberBinding as Binding;
if (b != null && b.Path != null)
{
propertyName = b.Path.Path;
}
if (string.IsNullOrEmpty(propertyName)) return;
}
ApplySort(lv.Items, propertyName);
SetCurrentSortColumn(gv, gvc);
CurrentSortColumnSetGlyph(gvc, lv);
}
public static void ApplySort(ICollectionView view, string propertyName)
{
if (string.IsNullOrEmpty(propertyName)) return;
ListSortDirection lsd = ListSortDirection.Ascending;
if (view.SortDescriptions.Count > 0)
{
SortDescription sd = view.SortDescriptions[0];
if (sd.PropertyName.Equals(propertyName))
{
if (sd.Direction == ListSortDirection.Ascending)
{
lsd = ListSortDirection.Descending;
}
else
{
lsd = ListSortDirection.Ascending;
}
}
view.SortDescriptions.Clear();
}
view.SortDescriptions.Add(new SortDescription(propertyName, lsd));
}
#endregion
public static T VisualUpwardSearch<T>(DependencyObject source)
where T : DependencyObject
{
return VisualUpwardSearch(source, x => x is T) as T;
}
public static DependencyObject VisualUpwardSearch(
DependencyObject source, Predicate<DependencyObject> match)
{
DependencyObject returnVal = source;
while (returnVal != null && !match(returnVal))
{
DependencyObject tempReturnVal = null;
if (returnVal is Visual || returnVal is Visual3D)
{
tempReturnVal = VisualTreeHelper.GetParent(returnVal);
}
if (tempReturnVal == null)
{
returnVal = LogicalTreeHelper.GetParent(returnVal);
}
else
{
returnVal = tempReturnVal;
}
}
return returnVal;
}
}
}
I also had this error. It worked normally after I clean up the cookies.
HTML5 comes with File API spec, which allows you to create applications that let the user interact with files locally; That means you can load files and render them in the browser without actually having to upload the files. Part of the File API is the FileReader interface which lets web applications asynchronously read the contents of files .
Here's a quick example that makes use of the FileReader
class to read an image as DataURL and renders a thumbnail by setting the src
attribute of an image tag to a data URL:
The html code:
<input type="file" id="files" />
<img id="image" />
The JavaScript code:
document.getElementById("files").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
// get loaded data and render thumbnail.
document.getElementById("image").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
};
Here's a good article on using the File APIs in JavaScript.
The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:
function handleFileSelect(evt) {_x000D_
var files = evt.target.files;_x000D_
_x000D_
// Loop through the FileList and render image files as thumbnails._x000D_
for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
// Only process image files._x000D_
if (!f.type.match('image.*')) {_x000D_
continue;_x000D_
}_x000D_
_x000D_
var reader = new FileReader();_x000D_
_x000D_
// Closure to capture the file information._x000D_
reader.onload = (function(theFile) {_x000D_
return function(e) {_x000D_
// Render thumbnail._x000D_
var span = document.createElement('span');_x000D_
span.innerHTML = _x000D_
[_x000D_
'<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
e.target.result,_x000D_
'" title="', escape(theFile.name), _x000D_
'"/>'_x000D_
].join('');_x000D_
_x000D_
document.getElementById('list').insertBefore(span, null);_x000D_
};_x000D_
})(f);_x000D_
_x000D_
// Read in the image file as a data URL._x000D_
reader.readAsDataURL(f);_x000D_
}_x000D_
}_x000D_
_x000D_
document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
If you're using Python 3, raw_input
has changed to input
Python 3 example:
line = input('Enter a sentence:')
I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:
SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;
Thanks for answering, it helped my train of thought.
The "input" tag doesn't support rows and cols attributes. This is why the best alternative is to use a textarea with rows and cols attributes. You can still add a "name" attribute and also there is a useful "wrap" attribute which can serve pretty well in various situations.
You are on the right track about hostvars
.
This magic variable is used to access information about other hosts.
hostvars
is a hash with inventory hostnames as keys.
To access fields of each host, use hostvars['test-1']
, hostvars['test2-1']
, etc.
ansible_ssh_host
is deprecated in favor of ansible_host
since 2.0.
So you should first remove "_ssh" from inventory hosts arguments (i.e. to become "ansible_user", "ansible_host", and "ansible_port"), then in your role call it with:
{{ hostvars['your_host_group'].ansible_host }}
Taking the top answer, as well as the suggestions from its comments, and modifying it to use SecureString instead of String, test for all control keys, and not error or write an extra "*" to the screen when the password length is 0, my solution is:
public static SecureString getPasswordFromConsole(String displayMessage) {
SecureString pass = new SecureString();
Console.Write(displayMessage);
ConsoleKeyInfo key;
do {
key = Console.ReadKey(true);
// Backspace Should Not Work
if (!char.IsControl(key.KeyChar)) {
pass.AppendChar(key.KeyChar);
Console.Write("*");
} else {
if (key.Key == ConsoleKey.Backspace && pass.Length > 0) {
pass.RemoveAt(pass.Length - 1);
Console.Write("\b \b");
}
}
}
// Stops Receving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);
return pass;
}
Let me explain a bit by bit.
0: standard input
1: standard output
2: standard error
>>
in command >> /dev/null 2>&1
appends the command output to /dev/null
.
command
=> 1 output on the terminal screen
=> 2 output on the terminal screen
command >> /dev/null
=> 1 output to /dev/null
=> 2 output on the terminal screen
/dev/null 2>&1
command >> /dev/null 2>&1
=> 1 output to /dev/null
=> 2 output is redirected to 1 which is now to /dev/null
i think you need to remove the ';' from the end of the java path.
Nothing else worked for me except, setting the path as:
C:\Program Files\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0
Another example. When building a complex map of maps, the computeIfAbsent() method is a replacement for map's get() method. Through chaining of computeIfAbsent() calls together, missing containers are constructed on-the-fly by provided lambda expressions:
// Stores regional movie ratings
Map<String, Map<Integer, Set<String>>> regionalMovieRatings = new TreeMap<>();
// This will throw NullPointerException!
regionalMovieRatings.get("New York").get(5).add("Boyhood");
// This will work
regionalMovieRatings
.computeIfAbsent("New York", region -> new TreeMap<>())
.computeIfAbsent(5, rating -> new TreeSet<>())
.add("Boyhood");
In the older versions it would default to the console subsystem even if you selected "empty project", but not in 2010, so you have to set it manually. To do this select the project in the solution explorer on the right or left (probably is already selected so you don't have to worry about this). Then select "project" from the menu bar drop down menus, then select "project_name properties" > "configuration properties" > "linker" > "system" and set the first property, the drop down "subsystem" property to "console (/SUBSYSTEM:CONSOLE)". The console window should now stay open after execution as usual.
If your table is only 2 columns across, you can easily reach the second td
with the adjacent sibling selector, which IE8 does support along with :first-child
:
.editor td:first-child
{
width: 150px;
}
.editor td:first-child + td input,
.editor td:first-child + td textarea
{
width: 500px;
padding: 3px 5px 5px 5px;
border: 1px solid #CCC;
}
Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td
, as suggested by James Allardice.
Active 1st tab
$("#workflowTab").tabs({ active: 0 });
Active last tab
$("#workflowTab").tabs({ active: -1 });
Active 2nd tab
$("#workflowTab").tabs({ active: 1 });
Its work like an array
here is my code..
const input = MobileNumberComponent.find('input')
// when
input.props().onChange({target: {
id: 'mobile-no',
value: '1234567900'
}});
MobileNumberComponent.update()
const Footer = (loginComponent.find('Footer'))
expect(Footer.find('Buttons').props().disabled).equals(false)
I have update my DOM with componentname.update()
And then checking submit button validation(disable/enable) with length 10 digit.
Here's a function that is also based on cloneNode
, but with an option to clone only the parent node and move all the children (to preserve their event listeners):
function recreateNode(el, withChildren) {
if (withChildren) {
el.parentNode.replaceChild(el.cloneNode(true), el);
}
else {
var newEl = el.cloneNode(false);
while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
el.parentNode.replaceChild(newEl, el);
}
}
Remove event listeners on one element:
recreateNode(document.getElementById("btn"));
Remove event listeners on an element and all of its children:
recreateNode(document.getElementById("list"), true);
If you need to keep the object itself and therefore can't use cloneNode
, then you have to wrap the addEventListener
function and track the listener list by yourself, like in this answer.
@dsimcha wrote: Counting sort: When you are sorting integers with a limited range
I would change that to:
Counting sort: When you sort positive integers (0 - Integer.MAX_VALUE-2 due to the pigeonhole).
You can always get the max and min values as an efficiency heuristic in linear time as well.
Also you need at least n extra space for the intermediate array and it is stable obviously.
/**
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
(even though it actually will allow to MAX_VALUE-2) see: Do Java arrays have a maximum size?
Also I would explain that radix sort complexity is O(wn) for n keys which are integers of word size w. Sometimes w is presented as a constant, which would make radix sort better (for sufficiently large n) than the best comparison-based sorting algorithms, which all perform O(n log n) comparisons to sort n keys. However, in general w cannot be considered a constant: if all n keys are distinct, then w has to be at least log n for a random-access machine to be able to store them in memory, which gives at best a time complexity O(n log n). (from wikipedia)
I strongly advise against using plain Win32 because it's pretty hard to make it work OK in all situations, it's pretty dull and tedious work and the Common Controls library isn't that complete. Also, most of the work has been done for you.
Every time I end up doing plain Win32 I have to spent at least a couple of hours on the most trivial tasks because I have to look up all the parameters, flags, functions, macros and figure out how to hook them up properly. I'd generally prefer a simple drag-and-drop don't-make-me-use-my-brains type of solution and just slam the thing together in 2 minutes.
As a lightweight toolkit I'd suggest omgui which has a clean and pretty API. It doesn't, however, come with any tools.
If you need tool support, you'll probably end up wanting to go for either MFC (resource editor built into Visual Studio) or Qt. I don't know if wxWidgets has any tools, but I presume it has.
Edit: David Citron mentions that apparently the resource editor in Visual Studio generates Win32 compatible resource files, so that's probably the preferred way to do things if you wanted to keep things simple.
object.runtimeType
returns the type of object
For example:
print("HELLO".runtimeType); //prints String
var x=0.0;
print(x.runtimeType); //prints double
I had the following error message Port 80 in use by "Unable to open process" with PID 4! Apache WILL NOT start without the configured ports free! You need to uninstall/disable/reconfigure the blocking application or reconfigure Apache and the Control Panel to listen on a different port Starting Check-Timer Control Panel Ready
opened the httpd.conf and changed the listen port from 80 to 1234 in both places
Listen 1234
Then go to Config for the xampp control panel and go to service and port setting and changed the port from 80 to 1234
That worked.
A note - when using ExtendScript JavaScript (the Adobe Scripting language used in applications like Photoshop CS3+), the character to use is "\r". "\n" will be interpreted as a font character, and many fonts will thus have a block character instead.
For example (to select a layer named 'Note' and add line feeds after all periods):
var layerText = app.activeDocument.artLayers.getByName('Note').textItem.contents;
layerText = layerText.replace(/\. /g,".\r");
the best way to find out all the combinations for large number of lists is:
import itertools
from pprint import pprint
inputdata = [
['a', 'b', 'c'],
['d'],
['e', 'f'],
]
result = list(itertools.product(*inputdata))
pprint(result)
the result will be:
[('a', 'd', 'e'),
('a', 'd', 'f'),
('b', 'd', 'e'),
('b', 'd', 'f'),
('c', 'd', 'e'),
('c', 'd', 'f')]
What worked for me was upgrading pandas to latest version:
From Command Line do:
conda update pandas
If you have a BASH shell on your mac/linux in-front of you, you try out the below steps to understand the redirection practically :
Create a 2 line script called zz.sh
#!/bin/bash
echo "Hello. This is a proper command"
junk_errorcommand
Currently, simply executing the script sends both STDOUT and STDERR to the screen.
./zz.sh
Now start with the standard redirection :
zz.sh > zfile.txt
In the above, "echo" (STDOUT) goes into the zfile.txt. Whereas "error" (STDERR) is displayed on the screen.
The above is the same as :
zz.sh 1> zfile.txt
Now you can try the opposite, and redirect "error" STDERR into the file. The STDOUT from "echo" command goes to the screen.
zz.sh 2> zfile.txt
Combining the above two, you get:
zz.sh 1> zfile.txt 2>&1
Explanation:
Eventually, you can pack the whole thing inside nohup command & to run it in the background:
nohup zz.sh 1> zfile.txt 2>&1&
Firstly add a dependency in the module:app
build.gradle file
compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.+'
Then, in the layout file
<pl.droidsonroids.gif.GifImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/mq_app"
/>
via Is there a way to link someone to a YouTube Video in HD 1080p quality?
Yes there is:
https://www.youtube.com/embed/Susj4jVWs0s?version=3&vq=hd720
options are:
default|none: vq=auto;
Code for auto: vq=auto;
Code for 2160p: vq=hd2160;
Code for 1440p: vq=hd1440;
Code for 1080p: vq=hd1080;
Code for 720p: vq=hd720;
Code for 480p: vq=large;
Code for 360p: vq=medium;
Code for 240p: vq=small;
As mentioned, you have to use the /embed/
or /v/
URL.
Note: Some copyrighted content doesn't support be played in this way
I think you could just do this:
$cookieString = password_hash($username, PASSWORD_DEFAULT);
Store $cookiestring
in the DB and and set it as a cookie. Also set the username of the person as a cookie. The whole point of a hash is that it can't be reverse-engineered.
When a user turns up, get the username from one cookie, than $cookieString
from another. If $cookieString
matches the one stored in the DB, then the user is authenticated. As password_hash uses a different salt each time, it is irrelevant as to what the clear text is.
The first value is the precision and the second is the scale, so 18,0
is essentially 18 digits with 0 digits after the decimal place. If you had 18,2
for example, you would have 18 digits, two of which would come after the decimal...
example of 18,2: 1234567890123456.12
There is no functional difference between numeric
and decimal
, other that the name and I think I recall that numeric came first, as in an earlier version.
And to answer, "can I add (-10) in that column?" - Yes, you can.
OK - so this issue has been driving me crazy - v 6.3.6 on Ubuntu Linux. None of the above solutions worked for me. Connecting to localhost mysql server previously always worked fine. Connecting to remote server always timed out - after about 60 seconds, sometimes after less time, sometimes more.
What finally worked for me was upgrading Workbench to 6.3.9 - no more dropped connections.
The following works. It only has to be set once in pure CSS. And it works more reliably than a JS function. Performance seems unaffected.
@-webkit-keyframes androidBugfix {from { padding: 0; } to { padding: 0; }}
body { -webkit-animation: androidBugfix infinite 1s; }
While calling/invoking your programme you can use this command : java [-options] className [args...]
in place of [-options] provide more memory e.g -Xmx1024m or more. but this is just a workaround, u have to change ur parsing mechanism.
if (typeof console != "undefined") {
...
}
Or better
if ((typeof console == "object") && (typeof console.profile == "function")) {
console.profile(f.constructor);
}
Works in all browsers
curl -X GET 'localhost:9200/foo/_search?q=*&pretty'
The code is correct so I'm guessing that you are using an older JDK. The javadoc for that method says it has been there since 1.6. At the command line type:
java -version
I'm guessing that you are not running 1.6
In spark 2.2 there are two ways to add constant value in a column in DataFrame:
1) Using lit
2) Using typedLit
.
The difference between the two is that typedLit
can also handle parameterized scala types e.g. List, Seq, and Map
Sample DataFrame:
val df = spark.createDataFrame(Seq((0,"a"),(1,"b"),(2,"c"))).toDF("id", "col1")
+---+----+
| id|col1|
+---+----+
| 0| a|
| 1| b|
+---+----+
1) Using lit
: Adding constant string value in new column named newcol:
import org.apache.spark.sql.functions.lit
val newdf = df.withColumn("newcol",lit("myval"))
Result:
+---+----+------+
| id|col1|newcol|
+---+----+------+
| 0| a| myval|
| 1| b| myval|
+---+----+------+
2) Using typedLit
:
import org.apache.spark.sql.functions.typedLit
df.withColumn("newcol", typedLit(("sample", 10, .044)))
Result:
+---+----+-----------------+
| id|col1| newcol|
+---+----+-----------------+
| 0| a|[sample,10,0.044]|
| 1| b|[sample,10,0.044]|
| 2| c|[sample,10,0.044]|
+---+----+-----------------+
getDay()
returns the day of the week. To get the date, use date.getDate()
. getMonth()
retrieves the month, but month is zero based, so using getMonth()+1
should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC
to the methods (e.g. date.getUTCFullYear()
, date.getUTCHours()
)
var timestamp = 1301090400,
date = new Date(timestamp * 1000),
datevalues = [
date.getFullYear(),
date.getMonth()+1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]
Assuming your DataRow
s inherit from your own type, say MyDataRowType
, this should work:
List<MyDataRowType> list = new List<MyDataRowType>();
foreach(DataRow row in dataTable.Rows)
{
list.Add((MyDataRowType)row);
}
This is assuming, as you said in a comment, that you're using .NET 2.0 and don't have access to the LINQ extension methods.
Use inet_ntop()
and inet_pton()
if you need it other way around. Do not use inet_ntoa(), inet_aton()
and similar as they are deprecated and don't support ipv6.
Here is a nice guide with quite a few examples.
// IPv4 demo of inet_ntop() and inet_pton()
struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];
// store this IP address in sa:
inet_pton(AF_INET, "192.0.2.33", &(sa.sin_addr));
// now get it back and print it
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);
printf("%s\n", str); // prints "192.0.2.33"
If you're doing something like trying to dynamically pass callbacks you could pass a single object as an argument. This gives you much greater control over which functions you want to you execute with any parameter.
function func_one(arg) {
console.log(arg)
};
function func_two(arg) {
console.log(arg+' make this different')
};
var obj = {
callbacks: [func_one, func_two],
params: ["something", "something else"];
};
function doSomething(obj) {
var n = obj.counter
for (n; n < (obj.callbacks.length - obj.len); n++) {
obj.callbacks[n](obj.params[n]);
}
};
obj.counter = 0;
obj.len = 0;
doSomething(obj);
//something
//something else make this different
obj.counter = 1;
obj.len = 0;
doSomething(obj);
//something else make this different
You can separate your commands using a semi colon:
cd /my_folder;rm *.jar;svn co path to repo;mvn compile package install
Was that what you mean?
As a result of the other posts, this is the shortest I could get:
DataTable destTable = sourceTable.Clone();
sourceTable.AsEnumerable().Where(row => /* condition */ ).ToList().ForEach(row => destTable.ImportRow(row));
Rails starting from version 5.2.3 has upcase_first method.
For example, "my Test string".upcase_first
will return My Test string
.
For a pure Ruby solution combine URI.parse
with CGI.parse
(this can be used even if Rails/Rack etc. are not required):
CGI.parse(URI.parse(url).query)
# => {"name1" => ["value1"], "name2" => ["value1", "value2", ...] }
Scroll down on that page and you'll see:
Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.
That's the SQLEXPRWT_x64_ENU.exe
download.... (WT = with tools)
Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.
That's the SQLEXPRADV_x64_ENU.exe
download ... (ADV = Advanced Services)
The SQLEXPR_x64_ENU.exe
file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.
A class
can only "implement" an interface
. A class only "extends" a class
. Likewise, an interface
can extend another interface
.
A class
can only extend one other class
. A class
can implement several interface
s.
If instead you are more interested in knowing when to use abstract class
es and interface
s, refer to this thread: Interface vs Abstract Class (general OO)
As a side note, you also should keep in mind that "escaping" means "using the back-slash as an indicator for special characters". You can put an end of line in a string doing that, for instance:
String foo = "Hello\
There";
I like using a function decorator. I added a class, which also times the function time. Assume gLog is a standard python logger:
class EnterExitLog():
def __init__(self, funcName):
self.funcName = funcName
def __enter__(self):
gLog.debug('Started: %s' % self.funcName)
self.init_time = datetime.datetime.now()
return self
def __exit__(self, type, value, tb):
gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time))
def func_timer_decorator(func):
def func_wrapper(*args, **kwargs):
with EnterExitLog(func.__name__):
return func(*args, **kwargs)
return func_wrapper
so now all you have to do with your function is decorate it and voila
@func_timer_decorator
def my_func():
cURL file object in procedural method:
$file = curl_file_create('full path/filename','extension','filename');
cURL file object in Oop method:
$file = new CURLFile('full path/filename','extension','filename');
$post= array('file' => $file);
$curl = curl_init();
//curl_setopt ...
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
Have a look at using something like
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded.
or
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that
let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"
It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?
Yes, we can run docker in docker, we'll need to attach the unix sockeet "/var/run/docker.sock" on which the docker daemon listens by default as volume to the parent docker using "-v /var/run/docker.sock:/var/run/docker.sock". Sometimes, permissions issues may arise for docker daemon socket for which you can write "sudo chmod 757 /var/run/docker.sock".
And also it would require to run the docker in privileged mode, so the commands would be:
sudo chmod 757 /var/run/docker.sock
docker run --privileged=true -v /var/run/docker.sock:/var/run/docker.sock -it ...
I realize this question is fairly old, but wanted to share a quick demo of group transforms, paths/shapes, and relative positioning, for anyone else who found their way here looking for more info:
If you are on android and using threetenbp you can use DateTimeUtils
instead.
ex:
Date date = DateTimeUtils.toDate(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
you can't use Date.from
since it's only supported on api 26+
The environment variables of a process exist at runtime, and are not stored in some file or so. They are stored in the process's own memory (that's where they are found to pass on to children). But there is a virtual file in
/proc/pid/environ
This file shows all the environment variables that were passed when calling the process (unless the process overwrote that part of its memory — most programs don't). The kernel makes them visible through that virtual file. One can list them. For example to view the variables of process 3940, one can do
cat /proc/3940/environ | tr '\0' '\n'
Each variable is delimited by a binary zero from the next one. tr replaces the zero into a newline.
You might sort the helper[]
array directly:
java.util.Arrays.sort(helper, 1, helper.length);
Sorts the array from index 1 to the end. Leaves the first item at index 0 untouched.
First of all jar
creates a jar, and does not run it. Try java -jar
instead.
Second, why do you pass the class twice, as FQCN (com.mycomp.myproj.dir2.MainClass2
) and as file (com/mycomp/myproj/dir2/MainClass2.class
)?
Edit:
It seems as if java -jar
requires a main class to be specified. You could try java -cp your.jar com.mycomp.myproj.dir2.MainClass2 ...
instead. -cp
sets the jar on the classpath and enables java to look up the main class there.
In CentOS 6(tested on Centos 7 too) you can't set short_open_tag in /etc/php.ini for php-fpm. You will have error:
ERROR: [/etc/php.ini:159] unknown entry 'short_open_tag'
ERROR: Unable to include /etc/php.ini from /etc/php-fpm.conf at line 159
ERROR: failed to load configuration file '/etc/php-fpm.conf'
ERROR: FPM initialization failed
You must edit config for your site, which can found in /etc/php-fpm.d/www.conf And write at end of file:
php_value[short_open_tag] = On
To compare two lists with the order preserved use,
assertThat(actualList, contains("item1","item2"));
From Apple Docs
You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."
As of C# 6 you can declare and initialise a 'read-only auto-property' in one line:
double FuelConsumption { get; } = 2;
You can set the value from the constructor but not other methods.
The following code makes it easy to refer to each of your DIVs and other HTML elements in JavaScript. This code should be included just before the tag, so that all of the HTML elements have been seen. It should be followed by your JavaScript code.
// For each element with an id (example: 'MyDIV') in the body, create a variable
// for easy reference. An example is below.
var D=document;
var id={}; // All ID elements
var els=document.body.getElementsByTagName('*');
for (var i = 0; i < els.length; i++)
{
thisid = els[i].id;
if (!thisid)
continue;
val=D.getElementById(thisid);
id[thisid]=val;
}
// Usage:
id.MyDIV.innerHTML="hello";
You can split the string into characters and filter it.
<?php
function filter_alphanum($string) {
$characters = str_split($string);
$alphaNumeric = array_filter($characters,"ctype_alnum");
return join($alphaNumeric);
}
$res = filter_alphanum("a!bc!#123");
print_r($res); // abc123
?>
Until today (9 jan 2014) the Bootstrap 3 still not support sub menu dropdown.
I searched Google about responsive navigation menu and found this is the best i though.
It is Smart menus http://www.smartmenus.org/
I hope this is the way out for anyone who want navigation menu with multilevel sub menu.
update 2015-02-17 Smart menus are now fully support Bootstrap element style for submenu. For more information please look at Smart menus website.
Given returned json from your://site.com:
[{text:"Text1", val:"Value1"},
{text:"Text2", val:"Value2"},
{text:"Text3", val:"Value3"}]
Use this:
$.getJSON("your://site.com", function(json){
$('#select').empty();
$('#select').append($('<option>').text("Select"));
$.each(json, function(i, obj){
$('#select').append($('<option>').text(obj.text).attr('value', obj.val));
});
});
I get no output when my Test/Test Settings/Default Processor Architecture setting and the assemblies that my test project references are not the same. Otherwise Trace.Writeline() works fine.
I use String.IsNullorEmpty often. It will work her because when DBNull is set to .ToString it returns empty.
if(!(String.IsNullorEmpty(rsData["usr.ursrdaystime"].toString())){
strLevel = rsData["usr.ursrdaystime"].toString();
}
I disagree with the predicate
if not orgs:
It should be
if not orgs.count():
I was having the same issue with a fairly large result set (~150k results). The operator is not overloaded in QuerySet, so the result is actually unpacked as a list before the check is made. In my case execution time went down by three orders.
Python (until version 3) supports "old-style" and new-style classes. New-style classes are derived from object
and are what you are using, and invoke their base class through super()
, e.g.
class X(object):
def __init__(self, x):
pass
def doit(self, bar):
pass
class Y(X):
def __init__(self):
super(Y, self).__init__(123)
def doit(self, foo):
return super(Y, self).doit(foo)
Because python knows about old- and new-style classes, there are different ways to invoke a base method, which is why you've found multiple ways of doing so.
For completeness sake, old-style classes call base methods explicitly using the base class, i.e.
def doit(self, foo):
return X.doit(self, foo)
But since you shouldn't be using old-style anymore, I wouldn't care about this too much.
Python 3 only knows about new-style classes (no matter if you derive from object
or not).
import org.apache.commons.codec.binary.Hex;
...
String hexString = Hex.encodeHexString(myString.getBytes(/* charset */));
http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Hex.html
Add a paramter as below in you in configuration while creating the exe
I hope it helps.
thanks...
/jav
you need to add 3 dependency ( API+ API implementation + log4j dependency)
Add also this
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.5</version>
</dependency>
# And to see log in command line , set log4j.properties
# Root logger option
log4j.rootLogger=INFO, file, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
#And to see log in file , set log4j.properties
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./logs/logging.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
The solution is very simple. git checkout <filename>
tries to check out file from the index, and therefore fails on merge.
What you need to do is (i.e. checkout a commit):
To checkout your own version you can use one of:
git checkout HEAD -- <filename>
or
git checkout --ours -- <filename>
(Warning!: If you are rebasing --ours
and --theirs
are swapped.)
or
git show :2:<filename> > <filename> # (stage 2 is ours)
To checkout the other version you can use one of:
git checkout test-branch -- <filename>
or
git checkout --theirs -- <filename>
or
git show :3:<filename> > <filename> # (stage 3 is theirs)
You would also need to run 'add' to mark it as resolved:
git add <filename>
You can do superscript with vertical-align: super
, (plus an accompanying font-size
reduction).
However, be sure to read the other answers here, particularly those by paulmurray and cletus, for useful information.
In the latest version of ggplot2, this can be more easy.
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))
See ?expansion()
for more details.
Since you are using bash, you don't need to create a child process for doing this. Here is one solution which performs it entirely within bash:
[[ $TEST =~ ^(.*):\ +(.*)$ ]] && TEST=${BASH_REMATCH[1]}:${BASH_REMATCH[2]}
Explanation: The groups before and after the sequence "colon and one or more spaces" are stored by the pattern match operator in the BASH_REMATCH array.
If all you want is to invoke foo
, and you prefer to propagate the exception as is (without wrapping), you can also just use Java's for
loop instead (after turning the Stream into an Iterable with some trickery):
for (A a : (Iterable<A>) as::iterator) {
a.foo();
}
This is, at least, what I do in my JUnit tests, where I don't want to go through the trouble of wrapping my checked exceptions (and in fact prefer my tests to throw the unwrapped original ones)
The os.exec*()
functions replace the current programm with the new one. When this programm ends so does your process. You probably want os.system()
.
I have another approach for Intellij users, and it is working very fine for me:
The problem is that buttonClickedEvent
is a member function and you need a pointer to member in order to invoke it.
Try this:
void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;
And then when you invoke it, you need an object of type MyClass
to do so, for example this
:
(this->*func)(<argument>);
http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm
For SQL Server use GetDate() or current_timestamp. You can format the result with the Convert(dataType,value,format). Tag your question with the correct Database Server.
The &
means that the function accepts the address (or reference) to a variable, instead of the value of the variable.
For example, note the difference between this:
void af(int& g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
And this (without the &
):
void af(int g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
Another option - to convert to C++ besides Shed Skin - is Pythran.
To quote High Performance Python by Micha Gorelick and Ian Ozsvald:
Pythran is a Python-to-C++ compiler for a subset of Python that includes partial
numpy
support. It acts a little like Numba and Cython—you annotate a function’s arguments, and then it takes over with further type annotation and code specialization. It takes advantage of vectorization possibilities and of OpenMP-based parallelization possibilities. It runs using Python 2.7 only.One very interesting feature of Pythran is that it will attempt to automatically spot parallelization opportunities (e.g., if you’re using a
map
), and turn this into parallel code without requiring extra effort from you. You can also specify parallel sections usingpragma omp
> directives; in this respect, it feels very similar to Cython’s OpenMP support.Behind the scenes, Pythran will take both normal Python and numpy code and attempt to aggressively compile them into very fast C++—even faster than the results of Cython.
You should note that this project is young, and you may encounter bugs; you should also note that the development team are very friendly and tend to fix bugs in a matter of hours.
You will have to over ride onPageStarted and onPageFinished callbacks
mWebView.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (progressBar!= null && progressBar.isShowing()) {
progressBar.dismiss();
}
progressBar = ProgressDialog.show(WebViewActivity.this, "Application Name", "Loading...");
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
select CONVERT((column_name) USING utf8) FROM table;
In my case, Workbench does not work. so i used the above solution to show blob data as text.
The tcpdf file that causes the "data has already been output" is in the tcpdf folder called tcpdf.php. You can modify it:
add the line ob_end_clean(); as below (3rd last line):
public function Output($name='doc.pdf', $dest='I') {
//LOTS OF CODE HERE....}
switch($dest) {
case 'I': {
// Send PDF to the standard output
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');}
//some code here....}
case 'D': { // download PDF as file
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');}
break;}
case 'F':
case 'FI':
case 'FD': {
// save PDF to a local file
//LOTS OF CODE HERE..... break;}
case 'E': {
// return PDF as base64 mime email attachment)
case 'S': {
// returns PDF as a string
return $this->getBuffer();
}
default: {
$this->Error('Incorrect output destination: '.$dest);
}
}
ob_end_clean(); //add this line here
return '';
}
Now lets look at your code.
I see you have $rs and $sql mixed up. These are 2 different things working together.
$conn=odbc_connect('northwind','****','*****');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql="SELECT * FROM products"; //is products your table name?
$rs=odbc_exec($conn,$sql);
if (!$rs) {
exit("Error in SQL");
}
while (odbc_fetch_row($rs)) {
$prodname=odbc_result($rs,"Product Name"); //but preferably never use spaces for table names.
$prodid=odbc_result($rs,"ProdID"); //prodID is assumed attribute
echo "$prodname";
echo "$prodid";
}
odbc_close($conn);
now you can use the $prodname and output it to the TCPDF output.
and I assume your are connecting to a MS access database.
Firefox contains a dns cache. To disable the DNS cache:
When disabled, Firefox will use the DNS cache provided by the OS.
Can be read, "For all s such that s does not equal s[start]"
To resolve problem go to the MDaemon-->setup-->Miscellaneous options-->Server-->SMTP Server Checks commands and headers for RFC Compliance
I came across the same error when trying to add the callback to an event listener. Strangely, setting the callback type to EventListener solved it. It looks more elegant than defining a whole function signature as a type, but I'm not sure if this is the correct way to do this.
class driving {
// the answer from this post - this works
// private callback: () => void;
// this also works!
private callback:EventListener;
constructor(){
this.callback = () => this.startJump();
window.addEventListener("keydown", this.callback);
}
startJump():void {
console.log("jump!");
window.removeEventListener("keydown", this.callback);
}
}
Do doubles always have 16 significant figures while floats always have 7 significant figures?
No. Doubles always have 53 significant bits and floats always have 24 significant bits (except for denormals, infinities, and NaN values, but those are subjects for a different question). These are binary formats, and you can only speak clearly about the precision of their representations in terms of binary digits (bits).
This is analogous to the question of how many digits can be stored in a binary integer: an unsigned 32 bit integer can store integers with up to 32 bits, which doesn't precisely map to any number of decimal digits: all integers of up to 9 decimal digits can be stored, but a lot of 10-digit numbers can be stored as well.
Why don't doubles have 14 significant figures?
The encoding of a double uses 64 bits (1 bit for the sign, 11 bits for the exponent, 52 explicit significant bits and one implicit bit), which is double the number of bits used to represent a float (32 bits).
I have tried but above not working after research found below the solution.
SELECT * FROM my_table where DATE(start_date) > '2011-01-01';
If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149
To summarize, open up a Terminal window and type the following command:
defaults write NSGlobalDomain KeyRepeat -int 0
More detail from the article:
Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:
defaults write NSGlobalDomain KeyRepeat -int 0
Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.
You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.
This usually occurs because either of the following are true:
Try getting some information about the certificate of the server and see if you need to install any specific certs on your client to get it to work.
you can do so by using the :before
or :after
pseudo. read more about it here http://astronautweb.co/snippet/font-awesome/
change your code to this
.lb-prev:hover {
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
opacity: 1;
text-decoration: none;
}
.lb-prev:before {
font-family: FontAwesome;
content: "\f053";
font-size: 30px;
}
do the same for the other icons. you might want to adjust the color and height of the icons too. anyway here is the fiddle hope this helps
Another alternative with .lastIndexOf
:
haystack.lastIndexOf(needle, 0) === 0
This looks backwards through haystack
for an occurrence of needle
starting from index 0
of haystack
. In other words, it only checks if haystack
starts with needle
.
In principle, this should have performance advantages over some other approaches:
haystack
.https://thomashunter.name/blog/simple-php-namespace-friendly-autoloader-class/
You’ll want to put your class files into a folder named Classes
, which is in the same directory as the entry point into your PHP application. If classes use namespaces, the namespaces will be converted into the directory structure.
Unlike a lot of other auto-loaders, underscores will not be converted into directory structures (it’s tricky to do PHP < 5.3 pseudo namespaces along with PHP >= 5.3 real namespaces).
<?php
class Autoloader {
static public function loader($className) {
$filename = "Classes/" . str_replace("\\", '/', $className) . ".php";
if (file_exists($filename)) {
include($filename);
if (class_exists($className)) {
return TRUE;
}
}
return FALSE;
}
}
spl_autoload_register('Autoloader::loader');
You’ll want to place the following code into your main PHP script (entry point):
require_once("Classes/Autoloader.php");
Here’s an example directory layout:
index.php
Classes/
Autoloader.php
ClassA.php - class ClassA {}
ClassB.php - class ClassB {}
Business/
ClassC.php - namespace Business; classC {}
Deeper/
ClassD.php - namespace Business\Deeper; classD {}
A one-line version of this excellent answer to plot the line of best fit is:
plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))
Using np.unique(x)
instead of x
handles the case where x
isn't sorted or has duplicate values.
You can use like this, it works!
WebProxy proxy = new WebProxy
{
Address = new Uri(""),
Credentials = new NetworkCredential("", "")
};
HttpClientHandler httpClientHandler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true
};
HttpClient client = new HttpClient(httpClientHandler);
HttpResponseMessage response = await client.PostAsync("...");