You could target all text boxes with input[type=text]
and then explicitly define the class for the textboxes who need it.
You can code like below :
input[type=text] {_x000D_
padding: 0;_x000D_
height: 30px;_x000D_
position: relative;_x000D_
left: 0;_x000D_
outline: none;_x000D_
border: 1px solid #cdcdcd;_x000D_
border-color: rgba(0, 0, 0, .15);_x000D_
background-color: white;_x000D_
font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
width: 526px;_x000D_
margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
I had the problem not able to load jar file in libs folder in Android Studio.
If you have added JAR file in libs folder, then just open build.gradle
file and save it without editing anything else. If you have added this line
compile fileTree(dir: 'libs', include: ['*.jar'])
save it and clean the project .. In next build time Android Studio will load the JAR file.
Hope this helps.
Add a toolbar to your xml
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment title"/>
</android.support.v7.widget.Toolbar>
Then inside your onCreateView method in the Fragment:
Toolbar toolbar = view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_button);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
One thing to remember: If you use a callback, make sure that your selector conforms to the following form:
- (void) image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo;
Otherwise, you'll crash with an error such as the following:
[NSInvocation setArgument:atIndex:]: index (2) out of bounds [-1, 1]
There is also possibility to use WebDriverWait with ExpectedConditions (to make sure that Frame will be available).
With string as parameter
(new WebDriverWait(driver, 5)).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("frame-name"));
With locator as a parameter
(new WebDriverWait(driver, 5)).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("frame-id")));
More info can be found here
Bootstrap / CSS
Use col-12
, btn-block
, w-100
, form-control
or width:100%
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<button class="btn btn-success col-12">
class="col-12"
</button>
<button class="btn btn-primary w-100">
class="w-100"
</button>
<button class="btn btn-secondary btn-block">
class="btn-block"
</button>
<button class="btn btn-success form-control">
class="form-control"
</button>
<button class="btn btn-danger" style="width:100%">
style="width:100%"
</button>
_x000D_
In my case, /storage/emulated/0/ corresponds to my device's root path. For example, when i take a photo with my phone's default camera application, the images are saved automatically /store/emulated/0/DCIM/Camera/mypicname.jpeg
For example, suppose that you want to store your pictures in /Pictures directory, namely in Pictures directory which exist in root directory. So you use the below code.
File storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES );
If you want to save the images in DCIM or Downloads directory, give the below arguments to the Environment.getExternalStoragePublicDirectory() method shown above.
Environment.DIRECTORY_DCIM
Environment.DIRECTORY_Downloads
Then specify your image name :
String imageFileName = "JPEG_" + timeStamp + "_";
Then create the file object as shown below. You specify the suffix as the 2nd argument.
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
Thus, to summarise the existing discussion, adding
cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5
to your plot, where 1.5 could be 2, 3, etc. and a value of 1 is the default will increase the font size.
x <- rnorm(100)
hist(x, xlim=range(x),
xlab= "Variable Lable", ylab="density", main="Title of plot", prob=TRUE)
hist(x, xlim=range(x),
xlab= "Variable Lable", ylab="density", main="Title of plot", prob=TRUE,
cex=1.5)
hist(x, xlim=range(x),
xlab= "Variable Lable", ylab="density", main="Title of plot", prob=TRUE,
cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5)
Just go to the (app level) build.gradle
file, give an empty space somewhere and click on sync, once gradle shows sync complete then the Error will be gone
def solve(s):
for i in s[:].split():
s = s.replace(i, i.capitalize())
return s
This is the actual code for work. .title() will not work at '12name' case
I use something like this (you should add code to deal with the various fails):
var response = RunTaskWithTimeout<ReturnType>(
(Func<ReturnType>)delegate { return SomeMethod(someInput); }, 30);
/// <summary>
/// Generic method to run a task on a background thread with a specific timeout, if the task fails,
/// notifies a user
/// </summary>
/// <typeparam name="T">Return type of function</typeparam>
/// <param name="TaskAction">Function delegate for task to perform</param>
/// <param name="TimeoutSeconds">Time to allow before task times out</param>
/// <returns></returns>
private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
{
Task<T> backgroundTask;
try
{
backgroundTask = Task.Factory.StartNew(TaskAction);
backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
}
catch (AggregateException ex)
{
// task failed
var failMessage = ex.Flatten().InnerException.Message);
return default(T);
}
catch (Exception ex)
{
// task failed
var failMessage = ex.Message;
return default(T);
}
if (!backgroundTask.IsCompleted)
{
// task timed out
return default(T);
}
// task succeeded
return backgroundTask.Result;
}
You can use:
type text1.txt >> combine.txt
echo >> combine.txt
type text2.txt >> combine.txt
or something like this:
echo blah >> combine.txt
echo blah2 >> combine.txt
echo >> combine.txt
echo other >> combine.txt
Yes, Its possible in SQL, but we can't set more than one primary keys in MsAccess. Then, I don't know about the other databases.
CREATE TABLE CHAPTER (
BOOK_ISBN VARCHAR(50) NOT NULL,
IDX INT NOT NULL,
TITLE VARCHAR(100) NOT NULL,
NUM_OF_PAGES INT,
PRIMARY KEY (BOOK_ISBN, IDX)
);
HTML Upload File ASP MVC 3.
Model: (Note that FileExtensionsAttribute is available in MvcFutures. It will validate file extensions client side and server side.)
public class ViewModel
{
[Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv",
ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
public HttpPostedFileBase File { get; set; }
}
HTML View:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.File, new { type = "file" })
@Html.ValidationMessageFor(m => m.File)
}
Controller action:
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
// Use your file here
using (MemoryStream memoryStream = new MemoryStream())
{
model.File.InputStream.CopyTo(memoryStream);
}
}
}
One solution to this problem is to use the Handler.postDelayed() method. Some Google training materials suggest the same solution.
@Override
public void onClick(View v) {
my_button.setBackgroundResource(R.drawable.icon);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
my_button.setBackgroundResource(R.drawable.defaultcard);
}
}, 2000);
}
However, some have pointed out that the solution above causes a memory leak because it uses a non-static inner and anonymous class which implicitly holds a reference to its outer class, the activity. This is a problem when the activity context is garbage collected.
A more complex solution that avoids the memory leak subclasses the Handler
and Runnable
with static inner classes inside the activity since static inner classes do not hold an implicit reference to their outer class:
private static class MyHandler extends Handler {}
private final MyHandler mHandler = new MyHandler();
public static class MyRunnable implements Runnable {
private final WeakReference<Activity> mActivity;
public MyRunnable(Activity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
public void run() {
Activity activity = mActivity.get();
if (activity != null) {
Button btn = (Button) activity.findViewById(R.id.button);
btn.setBackgroundResource(R.drawable.defaultcard);
}
}
}
private MyRunnable mRunnable = new MyRunnable(this);
public void onClick(View view) {
my_button.setBackgroundResource(R.drawable.icon);
// Execute the Runnable in 2 seconds
mHandler.postDelayed(mRunnable, 2000);
}
Note that the Runnable
uses a WeakReference to the Activity, which is necessary in a static class that needs access to the UI.
For options screens, especially where there are multiple radio groups, I like to use a grouped table view. Each group is a radio group and each cell a choice within the group. It is trivial to use the accessory view of a cell for a check mark indicating which option you want.
If only UIPickerView could be made just a little smaller or their gradients were a bit better suited to tiling two to a page...
git archive --format=zip --remote=ssh://<user>@<host>/repos/<repo name> <tag or HEAD> <filename> > <output file name>.zip
I've had this problem when trying to start a dotnet Core project using dotnet run when it tried to bind to the port.
The problem was caused by having a Visual Studio 2017 instance running with the project open - I'd previously started the project via VS for debugging and it appears that it was holding on to the port, even though debugging had finished and the application appeared closed.
Closing the Visual Studio instance and running "dotnet run" again solved the problem.
With C#6.0 you also have a new way of formatting date when using string interpolation e.g.
$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"
Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.
Its because of the float of the div. Add overflow: hidden
on the outside element.
<div style="overflow:hidden; margin:0 auto;width: 960px; min-height: 100px; background-color:orange;">
<div style="width:500px; height:200px; background-color:black; float:right">
</div>
</div>
Forge's SHA-256 implementation is fast and reliable.
To run tests on several SHA-256 JavaScript implementations, go to http://brillout.github.io/test-javascript-hash-implementations/.
The results on my machine suggests forge to be the fastest implementation and also considerably faster than the Stanford Javascript Crypto Library (sjcl) mentioned in the accepted answer.
Forge is 256 KB big, but extracting the SHA-256 related code reduces the size to 4.5 KB, see https://github.com/brillout/forge-sha256
This solution worked best for me. It uses jQuery and the iframe's ".load" event.
I just had the same problem and tested the methods mentioned above. After several trials, I realized that they are partially correct and are not the complete solution. I tested the below in Windows 10 and Anaconda 4.4.0 with python 3.6.
There are two ways to do even though they have only very small difference. Follow the way marneylc suggested above: i.e.
1) Open "Anaconda Prompt" and type jupyter notebook --generate-config
2) You find the file in C:\Users\username\.jupyter\jupyter_notebook_config.py
3) Change the line of #c.NotebookApp.notebook_dir = ''
to c.NotebookApp.notebook_dir = 'c:\test\your_root\'
4) Then, go to the shortcut of Jupyter Notebook located in C:\Users\User_name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)
5) Do the right click and go to the Properties
6) In the Target
field, remove %USERPROFILE%
as stenlytw suggested above.
7) Then, In the field of Start in
, type the same directory of c:\test\your_root\
in jupyter_notebook_config.py
8) Done!
As the simpler way, after step 3, go to C:\Users\User_name\Anaconda3\Scripts
4-2) You can see the file of jupyter-notebook.exe
and click it.
5-2) Then, the Jupyter start the folder you specified in jupyter_notebook_config.py
. So make the shortcut of this file.
6-2) Done.
By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once.
The first read in your case is being done when Web API is binding your model, after that the Request.Content
will not return anything.
You can remove the contact
from your action parameters, get the content and deserialize it manually into object (for example with Json.NET):
[HttpPut]
public HttpResponseMessage Put(int accountId)
{
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
CONTACT contact = JsonConvert.DeserializeObject<CONTACT>(jsonContent);
...
}
That should do the trick (assuming that accountId
is URL parameter so it will not be treated as content read).
Why the loop?
You could simply do this:
{% if 'priority' in data %}
<p>Priority: {{ data['priority'] }}</p>
{% endif %}
When you were originally doing your string comparison, you should have used ==
instead.
You can use destructuring to only focus on the part of your interest.
So you can do:
let str = "My cow always gives milk";
let [, result] = str.match(/\bcow\s+(.*?)\s+milk\b/) || [];
console.log(result);
_x000D_
In this way you ignore the first part (the complete match) and only get the capture group's match. The addition of || []
may be interesting if you are not sure there will be a match at all. In that case match
would return null
which cannot be destructured, and so we return []
instead in that case, and then result
will be null
.
The additional \b
ensures the surrounding words "cow" and "milk" are really separate words (e.g. not "milky"). Also \s+
is needed to avoid that the match includes some outer spacing.
Follow these steps- 1.go to config.inc.php file and find - $cfg['Servers'][$i]['auth_type']
2.change the value of $cfg['Servers'][$i]['auth_type'] to 'cookie' or 'http'.
3.find $cfg['Servers'][$i]['AllowNoPassword'] and change it's value to true.
Now whenever you want to login, enter root as your username,skip the password and go ahead pressing the submit button..
Note- if you choose authentication type as cookie then whenever you will close the browser and reopen it ,again you have to login.
As of Visual Studio 2019, the modern .csproj
format supports adding a condition directly on the Target
element:
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(Configuration)' == 'Debug'">
<Exec Command="nswag run nswag.json" />
</Target>
The UI doesn't provide a way to set this up, but it does appear to safely leave the Configuration
attribute in place if you make changes via the UI.
In my case it is similar to @Michael Easter: I got a problem in a job due to lack of disk space. I cleared some space, restarted Jenkins but still the problem persisted.
The solution was to go to Jenkins -> Manage Jenkins -> Manage Nodes and just Click on the button to update the status.
I would recommend log4net.
You would need multiple log files. So multiple file appenders. Plus you can create the file appenders dynamically.
Sample Code:
using log4net;
using log4net.Appender;
using log4net.Layout;
using log4net.Repository.Hierarchy;
// Set the level for a named logger
public static void SetLevel(string loggerName, string levelName)
{
ILog log = LogManager.GetLogger(loggerName);
Logger l = (Logger)log.Logger;
l.Level = l.Hierarchy.LevelMap[levelName];
}
// Add an appender to a logger
public static void AddAppender(string loggerName, IAppender appender)
{
ILog log = LogManager.GetLogger(loggerName);
Logger l = (Logger)log.Logger;
l.AddAppender(appender);
}
// Create a new file appender
public static IAppender CreateFileAppender(string name, string fileName)
{
FileAppender appender = new
FileAppender();
appender.Name = name;
appender.File = fileName;
appender.AppendToFile = true;
PatternLayout layout = new PatternLayout();
layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n";
layout.ActivateOptions();
appender.Layout = layout;
appender.ActivateOptions();
return appender;
}
// In order to set the level for a logger and add an appender reference you
// can then use the following calls:
SetLevel("Log4net.MainForm", "ALL");
AddAppender("Log4net.MainForm", CreateFileAppender("appenderName", "fileName.log"));
// repeat as desired
Sources/Good links:
Log4Net: Programmatically specify multiple loggers (with multiple file appenders)
Adding appenders programmatically
How to configure log4net programmatically from scratch (no config)
Plus the log4net also allows to write into event log as well. Everything is configuration based, and the configuration can be loaded dynamically from xml at runtime as well.
Edit 2:
One way to switch log files on the fly: Log4Net configuration file supports environment variables:
Environment.SetEnvironmentVariable("log4netFileName", "MyApp.log");
and in the log4net config:
<param name="File" value="${log4netFileName}".log/>
Here's what worked for me:
#div {
display: flex;
justify-content: center;
}
#table {
align-self: center;
}
And this aligned it vertically and horizontally.
In the converter of the chosen solution, you should add values.Clone() otherwise the parameters in the command end null
public class YourConverter : IMultiValueConverter
{
public object Convert(object[] values, ...)
{
return values.Clone();
}
...
}
This works in Windows; didn't check Linux but don't see why it wouldn't work. Download the zip files for 5.6.8 portable. Unzip the files and copy the xampp/htdocs to the xampp/htdocs in your install directory.
In VB.net use for the Sub:
Private Sub dgv_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgv.MouseUp
' deselezionare se click su vuoto
If e.Button = MouseButtons.Left Then
' Check the HitTest information for this click location
If Equals(dgv.HitTest(e.X, e.Y), DataGridView.HitTestInfo.Nowhere) Then
dgv.ClearSelection()
dgv.CurrentCell = Nothing
End If
End If
End Sub
You can extend the RecursiveFilterIterator class like this:
class ExtensionFilter extends RecursiveFilterIterator
{
/**
* Hold the extensions pass to the class constructor
*/
protected $extensions;
/**
* ExtensionFilter constructor.
*
* @param RecursiveIterator $iterator
* @param string|array $extensions Extension to filter as an array ['php'] or
* as string with commas in between 'php, exe, ini'
*/
public function __construct(RecursiveIterator $iterator, $extensions)
{
parent::__construct($iterator);
$this->extensions = is_array($extensions) ? $extensions : array_map('trim', explode(',', $extensions));
}
public function accept()
{
if ($this->hasChildren()) {
return true;
}
return $this->current()->isFile() &&
in_array(strtolower($this->current()->getExtension()), $this->extensions);
}
public function getChildren()
{
return new self($this->getInnerIterator()->getChildren(), $this->extensions);
}
Now you can instantiate RecursiveDirectoryIterator with path as an argument like this:
$iterator = new RecursiveDirectoryIterator('\path\to\dir');
$iterator = new ExtensionFilter($iterator, 'xml, php, ini');
foreach($iterator as $file)
{
echo $file . '<br />';
}
This will list files under the current folder only.
To get the files in subdirectories also,
pass the $iterator ( ExtensionFIlter Iterator) to RecursiveIteratorIterator as argument:
$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
Now run the foreach loop on this iterator. You will get the files with specified extension
Note:-- Also make sure to run the ExtensionFilter before RecursiveIteratorIterator, otherwise you will get all the files
You can 'slice' a string
very easily, just like you'd pull items from a list
:
a_string = 'This is a string'
To get the first 4 letters:
first_four_letters = a_string[:4]
>>> 'This'
Or the last 5:
last_five_letters = a_string[-5:]
>>> 'string'
So applying that logic to your problem:
the_string = '416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f '
first_32_chars = the_string[:32]
>>> 416d76b8811b0ddae2fdad8f4721ddbe
If you like the idea of Views, but are worried about performance you can get Oracle to create a cached table representing the view which oracle keeps up to date.
See materialized views
document.all() is a non-standard way of accessing DOM elements. It's been deprecated from a few browsers. It gives you access to all sub elements on your document.
document.getElementById() is a standard and fully supported. Each element have a unique id on the document.
If you have:
<div id="testing"></div>
Using
document.getElementById("testing");
Will have access to that specific div.
I needed my ASP.NET drop down list to take up all available space, and this is all I put in the CSS and it is working in Firefox and IE11:
width: 100%
I had to add the CSS class into the asp:DropDownList element
You can use Task.WaitAny
to wait the first of multiple tasks.
You could create two additional tasks (that complete after the specified timeouts) and then use WaitAny
to wait for whichever completes first. If the task that completed first is your "work" task, then you're done. If the task that completed first is a timeout task, then you can react to the timeout (e.g. request cancellation).
I have written a complete article at Spring Boot JPA Multiple Data Sources Example. In this article, we will learn how to configure multiple data sources and connect to multiple databases in a typical Spring Boot web application. We will use Spring Boot 2.0.5, JPA, Hibernate 5, Thymeleaf and H2 database to build a simple Spring Boot multiple data sources web application.
I was struggling with this, my app was installing but not complete (almost 60% I can say) in iOS8, but in iOS7.1 it was working as expected. The error message popped was:
"Cannot install at this time".
Finally Zillan's link helped me to get apple documentation. So, check:
ax.init.itunes.apple.com
is not getting blocked by your firewall/proxy (Just type this address in safari, a blank page must load). As soon as I changed the proxy it installed completely. Hope it will help someone.
If you just want to have a string representation of an object, you could use the JSON.stringify
function, using a JSON library.
I faced the same issue today,
And solved it easily by following points
1) Start the StandAlone SDK manager (To open the standalone sdk manager - Tools>Android>SDKManager> at Bottom YOu will see a link to launch StandAlone SDK manager)
2) Delete tha package of SDK Build Tools that you have already installed for e.g 24.0.0 rc4.
3) Close the standalone SDK manager then Restart Android Studio.
4) Once after restart the gradle will start building the project and you will get an alert download the package of SDK build tool and Sync. CLick on that and you will start downloading like that...
I hope this helps
for k, m in self.materials.items():
example:
miles_dict = {'Monday':1, 'Tuesday':2.3, 'Wednesday':3.5, 'Thursday':0.9}
for k, v in miles_dict.items():
print("%s: %s" % (k, v))
//For proper line spacing
NSString *text1 = @"Hello";
NSString *text2 = @"\nWorld";
UIFont *text1Font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:10];
NSMutableAttributedString *attributedString1 =
[[NSMutableAttributedString alloc] initWithString:text1 attributes:@{ NSFontAttributeName : text1Font }];
NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle1 setAlignment:NSTextAlignmentCenter];
[paragraphStyle1 setLineSpacing:4];
[attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [attributedString1 length])];
UIFont *text2Font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:16];
NSMutableAttributedString *attributedString2 =
[[NSMutableAttributedString alloc] initWithString:text2 attributes:@{NSFontAttributeName : text2Font }];
NSMutableParagraphStyle *paragraphStyle2 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle2 setLineSpacing:4];
[paragraphStyle2 setAlignment:NSTextAlignmentCenter];
[attributedString2 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle2 range:NSMakeRange(0, [attributedString2 length])];
[attributedString1 appendAttributedString:attributedString2];
For this html:
<div class="outer">
<div class="inner"></div>
</div>
This selector should work:
$('.outer > .inner')
Use the wait
built-in:
process1 &
process2 &
process3 &
process4 &
wait
process5 &
process6 &
process7 &
process8 &
wait
For the above example, 4 processes process1
... process4
would be started in the background, and the shell would wait until those are completed before starting the next set.
From the GNU manual:
wait [jobspec or pid ...]
Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
File SongsTableSeeder.php should be in database/seeds directory or in its subdirectory.
You need to run:
composer dump-autoload
and then:
php artisan db:seed
or:
php artisan db:seed --class=SongsTableSeeder
nmap is a useful tool for this kind of thing
ps aux | grep manage
ubuntu 3438 127.0.0 2.3 40256 14064 pts/0 T 06:47 0:00 python manage.py runserver
kill -9 3438
Your project path contains Chinese characters,
em: F:\??\Yourproject
Please rename the path English characters:
em: F:\Data\Yourproject
As others have pointed out you need the quotes, but I just want to point out that there's a shorthand method of writing this same line of code
var htmlString="<?=$htmlString?>";
See you can leave out the "php echo" stuff and replace it with a simple "=".
You can use the formula INDIRECT()
.
This basically takes a string and treats it as a reference. In your case, you would use:
=INDIRECT("'"&A5&"'!G7")
The double quotes are to show that what's inside are strings, and only A5
here is a reference.
You can use:
String.format("%02d", myNumber)
See also the javadocs
Copy this code and save it as DelOldFiles.vbs
.
USAGE IN CMD : cscript //nologo DelOldFiles.vbs 15
15 means to delete files older than 15 days in past.
'copy from here
Function DeleteOlderFiles(whichfolder)
Dim fso, f, f1, fc, n, ThresholdDate
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(whichfolder)
Set fc = f.Files
Set objArgs = WScript.Arguments
n = 0
If objArgs.Count=0 Then
howmuchdaysinpast = 0
Else
howmuchdaysinpast = -objArgs(0)
End If
ThresholdDate = DateAdd("d", howmuchdaysinpast, Date)
For Each f1 in fc
If f1.DateLastModified<ThresholdDate Then
Wscript.StdOut.WriteLine f1
f1.Delete
n = n + 1
End If
Next
Wscript.StdOut.WriteLine "Deleted " & n & " file(s)."
End Function
If Not WScript.FullName = WScript.Path & "\cscript.exe" Then
WScript.Echo "USAGE ONLY IN COMMAND PROMPT: cscript DelOldFiles.vbs 15" & vbCrLf & "15 means to delete files older than 15 days in past."
WScript.Quit 0
End If
DeleteOlderFiles(".")
'to here
All in python (using psycopg2
), create the empty table first then use copy_expert
to load the csv into it. It should handle for empty values.
import psycopg2
conn = psycopg2.connect(host="hosturl", database="db_name", user="username", password="password")
cur = conn.cursor()
cur.execute("CREATE TABLE schema.destination_table ("
"age integer, "
"first_name varchar(20), "
"last_name varchar(20)"
");")
with open(r'C:/tmp/people.csv', 'r') as f:
next(f) # Skip the header row. Or remove this line if csv has no header.
conn.cursor.copy_expert("""COPY schema.destination_table FROM STDIN WITH (FORMAT CSV)""", f)
Currently and unfortunately we can't do anything to stop the thread....
Adding something to Matt's answer we can call interrupt()
but that doesn't stop thread... Just tells the system to stop the thread when system wants to kill some threads. Rest is done by system, and we can check it by calling interrupted()
.
[p.s. : If you are really going with interrupt()
I would ask you to do some experiments with a short sleep after calling interrupt()
]
View source is not disabled in my browser (Chrome).
But they have added a lot of blank lines to the source, so you have to scroll down to view it. Try to scroll down and you will see.
the disabled right click is possible with javascript, but dont do it. Its very irritating for the user.
Apart from HTML 5 data-tip You can use css also for making a totally customizable tooltip to be used anywhere throughout your markup.
/* ToolTip classses */ _x000D_
.tooltip {_x000D_
display: inline-block; _x000D_
}_x000D_
.tooltip .tooltiptext {_x000D_
margin-left:9px;_x000D_
width : 320px;_x000D_
visibility: hidden;_x000D_
background-color: #FFF;_x000D_
border-radius:4px;_x000D_
border: 1px solid #aeaeae;_x000D_
position: absolute;_x000D_
z-index: 1;_x000D_
padding: 5px;_x000D_
margin-top : -15px; _x000D_
opacity: 0;_x000D_
transition: opacity 0.5s;_x000D_
}_x000D_
.tooltip .tooltiptext::after {_x000D_
content: " ";_x000D_
position: absolute;_x000D_
top: 5%;_x000D_
right: 100%; _x000D_
margin-top: -5px;_x000D_
border-width: 5px;_x000D_
border-style: solid;_x000D_
border-color: transparent #aeaeae transparent transparent;_x000D_
}_x000D_
_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
}
_x000D_
<div class="tooltip">_x000D_
<input type="text" />_x000D_
<span class="tooltiptext">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </span>_x000D_
</div>
_x000D_
FYI: g++ offers the non-standard __PRETTY_FUNCTION__ macro. Until just now I did not know about C99 __func__ (thanks Evan!). I think I still prefer __PRETTY_FUNCTION__ when it's available for the extra class scoping.
PS:
static string getScopedClassMethod( string thePrettyFunction )
{
size_t index = thePrettyFunction . find( "(" );
if ( index == string::npos )
return thePrettyFunction; /* Degenerate case */
thePrettyFunction . erase( index );
index = thePrettyFunction . rfind( " " );
if ( index == string::npos )
return thePrettyFunction; /* Degenerate case */
thePrettyFunction . erase( 0, index + 1 );
return thePrettyFunction; /* The scoped class name. */
}
I ran into this while I was learning Go 2 years ago, so I declared my own function.
// UNUSED allows unused variables to be included in Go programs
func UNUSED(x ...interface{}) {}
And then you can use it like so:
UNUSED(x)
UNUSED(x, y)
UNUSED(x, y, z)
The great thing about it is, you can pass anything into UNUSED.
Is it better than the following?
_, _, _ = x, y, z
That's up to you.
Check that you spelled the branch name correctly. I was rebasing a story branch (i.e. branch_name
) and forgot the story part. (i.e. story/branch_name
) and then git spit this error at me which didn't make much sense in this context.
In addition to the above answers you can also use .once
in a similar way to .output
. This outputs only the next query to the specified file, so that you don't have to follow with .output stdout
.
So in the above example
.mode csv
.headers on
.once test.csv
select * from tbl1;
Not sure if there was file corruption or what, but after confirming proper pom configuration I was able to resolve this issue by deleting the jar from my local m2 repository, forcing Maven to download it again when I ran the tests.
If you use CMake you have to set WIN32 flag in add_executable
add_executable(${name} WIN32 ${source_files})
See CMake Doc for more information.
You can also use shorthand for describe as desc
for table description.
desc [db_name.]table_name;
or
use db_name;
desc table_name;
You can also use explain
for table description.
explain [db_name.]table_name;
See official doc
Will give output like:
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int(10) | NO | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
| age | int(10) | YES | | NULL | |
| sex | varchar(10) | YES | | NULL | |
| sal | int(10) | YES | | NULL | |
| location | varchar(20) | YES | | Pune | |
+----------+-------------+------+-----+---------+-------+
There's no built-in method for doing this in Python 2. If you need this, you need to write a prepend()
method/function that operates on the OrderedDict
internals with O(1) complexity.
For Python 3.2 and later, you should use the move_to_end
method. The method accepts a last
argument which indicates whether the element will be moved to the bottom (last=True
) or the top (last=False
) of the OrderedDict
.
Finally, if you want a quick, dirty and slow solution, you can just create a new OrderedDict
from scratch.
Details for the four different solutions:
OrderedDict
and add a new instance methodfrom collections import OrderedDict
class MyOrderedDict(OrderedDict):
def prepend(self, key, value, dict_setitem=dict.__setitem__):
root = self._OrderedDict__root
first = root[1]
if key in self:
link = self._OrderedDict__map[key]
link_prev, link_next, _ = link
link_prev[1] = link_next
link_next[0] = link_prev
link[0] = root
link[1] = first
root[1] = first[0] = link
else:
root[1] = first[0] = self._OrderedDict__map[key] = [root, first, key]
dict_setitem(self, key, value)
Demo:
>>> d = MyOrderedDict([('a', '1'), ('b', '2')])
>>> d
MyOrderedDict([('a', '1'), ('b', '2')])
>>> d.prepend('c', 100)
>>> d
MyOrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> d.prepend('a', d['a'])
>>> d
MyOrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> d.prepend('d', 200)
>>> d
MyOrderedDict([('d', 200), ('a', '1'), ('c', 100), ('b', '2')])
OrderedDict
objectsThis function does the same thing by accepting the dict object, key and value. I personally prefer the class:
from collections import OrderedDict
def ordered_dict_prepend(dct, key, value, dict_setitem=dict.__setitem__):
root = dct._OrderedDict__root
first = root[1]
if key in dct:
link = dct._OrderedDict__map[key]
link_prev, link_next, _ = link
link_prev[1] = link_next
link_next[0] = link_prev
link[0] = root
link[1] = first
root[1] = first[0] = link
else:
root[1] = first[0] = dct._OrderedDict__map[key] = [root, first, key]
dict_setitem(dct, key, value)
Demo:
>>> d = OrderedDict([('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'c', 100)
>>> d
OrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'a', d['a'])
>>> d
OrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> ordered_dict_prepend(d, 'd', 500)
>>> d
OrderedDict([('d', 500), ('a', '1'), ('c', 100), ('b', '2')])
OrderedDict.move_to_end()
(Python >= 3.2)Python 3.2 introduced the OrderedDict.move_to_end()
method. Using it, we can move an existing key to either end of the dictionary in O(1) time.
>>> d1 = OrderedDict([('a', '1'), ('b', '2')])
>>> d1.update({'c':'3'})
>>> d1.move_to_end('c', last=False)
>>> d1
OrderedDict([('c', '3'), ('a', '1'), ('b', '2')])
If we need to insert an element and move it to the top, all in one step, we can directly use it to create a prepend()
wrapper (not presented here).
OrderedDict
- slow!!!If you don't want to do that and performance is not an issue then easiest way is to create a new dict:
from itertools import chain, ifilterfalse
from collections import OrderedDict
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen_add = seen.add
if key is None:
for element in ifilterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element
d1 = OrderedDict([('a', '1'), ('b', '2'),('c', 4)])
d2 = OrderedDict([('c', 3), ('e', 5)]) #dict containing items to be added at the front
new_dic = OrderedDict((k, d2.get(k, d1.get(k))) for k in \
unique_everseen(chain(d2, d1)))
print new_dic
output:
OrderedDict([('c', 3), ('e', 5), ('a', '1'), ('b', '2')])
Just to share my idea...
I created a custom class to inherit the Label class. I added a private variable assigned as a Tooltip class and a public property, TooltipText. Then, gave it a MouseEnter delegate method. This is an easy way to work with multiple Label controls and not have to worry about assigning your Tooltip control for each Label control.
public partial class ucLabel : Label
{
private ToolTip _tt = new ToolTip();
public string TooltipText { get; set; }
public ucLabel() : base() {
_tt.AutoPopDelay = 1500;
_tt.InitialDelay = 400;
// _tt.IsBalloon = true;
_tt.UseAnimation = true;
_tt.UseFading = true;
_tt.Active = true;
this.MouseEnter += new EventHandler(this.ucLabel_MouseEnter);
}
private void ucLabel_MouseEnter(object sender, EventArgs ea)
{
if (!string.IsNullOrEmpty(this.TooltipText))
{
_tt.SetToolTip(this, this.TooltipText);
_tt.Show(this.TooltipText, this.Parent);
}
}
}
In the form or user control's InitializeComponent method (the Designer code), reassign your Label control to the custom class:
this.lblMyLabel = new ucLabel();
Also, change the private variable reference in the Designer code:
private ucLabel lblMyLabel;
If you want to generate random numbers in range including '0' , use the following while 'max' is the maximum number in the range.
Random rand = new Random()
random_num = rand.nextInt(max+1)
You can use %2F
if using it this way:
?param1=value1¶m2=value%2Fvalue
but if you use /param1=value1/param2=value%2Fvalue
it will throw an error.
Yes you can handle with the catch operator like this and show alert as you want but firstly you have to import Rxjs
for the same like this way
import {Observable} from 'rxjs/Rx';
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
if (res.status === 201) {
return [{ status: res.status, json: res }]
}
else if (res.status === 200) {
return [{ status: res.status, json: res }]
}
}
}).catch((error: any) => {
if (error.status === 500) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 400) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 409) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 406) {
return Observable.throw(new Error(error.status));
}
});
}
also you can handel error (with err block) that is throw by catch block while .map
function,
like this -
...
.subscribe(res=>{....}
err => {//handel here});
as required for any status without checking particluar one you can try this: -
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
if (res.status === 201) {
return [{ status: res.status, json: res }]
}
else if (res.status === 200) {
return [{ status: res.status, json: res }]
}
}
}).catch((error: any) => {
if (error.status < 400 || error.status ===500) {
return Observable.throw(new Error(error.status));
}
})
.subscribe(res => {...},
err => {console.log(err)} );
Another simpler option is to do:
> x = c(1, 1, 2, 4, 5, 2, 1, 3, 2)
> x[x==1] <- 0
> x
[1] 0 0 2 4 5 2 0 3 2
you can also use
Dim intValue as integer = 65 ' letter A for instance
Dim strValue As String = Char.ConvertFromUtf32(intValue)
this doesn't requirement Microsoft.VisualBasic reference
If this is part of a batch script (.bat
file) and you have a large list of files, you can use a multi-line ^
, and optional /Y
flag to suppresses prompting to confirm you want to overwrite an existing destination file.
REM Concatenate several files to one
COPY /Y ^
this_is_file_1.csv + ^
this_is_file_2.csv + ^
this_is_file_3.csv + ^
this_is_file_4.csv + ^
this_is_file_5.csv + ^
this_is_file_6.csv + ^
this_is_file_7.csv + ^
this_is_file_8.csv + ^
this_is_file_9.csv ^
output_file.csv
This is tidier than performing the command on one line.
You could also use
ImageIcon background = new ImageIcon("Background/background.png");
JLabel label = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(background);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(label);
if your working with a absolut value as layout.
I think this code may be help you:
string str = char.ConvertFromUtf32(65)
Compile Time:
Things that are done at compile time incur (almost) no cost when the resulting program is run, but might incur a large cost when you build the program. Run-Time:
More or less the exact opposite. Little cost when you build, more cost when the program is run.
From the other side; If something is done at compile time, it runs only on your machine and if something is run-time, it run on your users machine.
The easiest way is probably with VLOOKUP()
. This will require the 2nd worksheet to have the employee number column sorted though. In newer versions of Excel, apparently sorting is no longer required.
For example, if you had a "Sheet2" with two columns - A = the employee number, B = the employee's name, and your current worksheet had employee numbers in column D and you want to fill in column E, in cell E2, you would have:
=VLOOKUP($D2, Sheet2!$A$2:$B$65535, 2, FALSE)
Then simply fill this formula down the rest of column D.
Explanation:
$D2
specifies the value to search for.Sheet2!$A$2:$B$65535
specifies the range of cells to search in. Excel will search for the value in the first column of this range (in this case Sheet2!A2:A65535
). Note I am assuming you have a header cell in row 1.2
specifies a 1-based index of the column to return from within the searched range. The value of 2
will return the second column in the range Sheet2!$A$2:$B$65535
, namely the value of the B
column.FALSE
says to only return exact matches.>>> s = 'abcd'
>>> len(s)
4
Send the data from the form:
$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
type: "PUT"
url: url
dataType: "script"
data: postData
DECLARE
a VARCHAR2(30);
b VARCHAR2(30);
c VARCHAR2(30);
BEGIN
a := ' Abc ';
b := ' def ';
c := a || b;
DBMS_OUTPUT.PUT_LINE(c);
END;
output:: Abc def
Use Reflection:
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
}
for Excel - what tools/reference item must be added to gain access to BindingFlags, as there is no "System.Reflection" entry in the list
Edit: You can also specify a BindingFlags value to type.GetProperties()
:
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);
That will restrict the returned properties to public instance properties (excluding static properties, protected properties, etc).
You don't need to specify BindingFlags.GetProperty
, you use that when calling type.InvokeMember()
to get the value of a property.
Simon's answer and Volcano's together explain what you're doing wrong, and Simon explains how you can fix it by redesigning your interface.
But if you really need to read 1 character, and then later read 1 line, you can do that. It's not trivial, and it's different on Windows vs. everything else.
There are actually three cases: a Unix tty, a Windows DOS prompt, or a regular file (redirected file/pipe) on either platform. And you have to handle them differently.
First, to check if stdin is a tty (both Windows and Unix varieties), you just call sys.stdin.isatty()
. That part is cross-platform.
For the non-tty case, it's easy. It may actually just work. If it doesn't, you can just read from the unbuffered object underneath sys.stdin
. In Python 3, this just means sys.stdin.buffer.raw.read(1)
and sys.stdin.buffer.raw.readline()
. However, this will get you encoded bytes, rather than strings, so you will need to call .decode(sys.stdin.decoding)
on the results; you can wrap that all up in a function.
For the tty case on Windows, however, input will still be line buffered even on the raw buffer. The only way around this is to use the Console I/O functions instead of normal file I/O. So, instead of stdin.read(1)
, you do msvcrt.getwch()
.
For the tty case on Unix, you have to set the terminal to raw mode instead of the usual line-discipline mode. Once you do that, you can use the same sys.stdin.buffer.read(1)
, etc., and it will just work. If you're willing to do that permanently (until the end of your script), it's easy, with the tty.setraw
function. If you want to return to line-discipline mode later, you'll need to use the termios
module. This looks scary, but if you just stash the results of termios.tcgetattr(sys.stdin.fileno())
before calling setraw
, then do termios.tcsetattr(sys.stdin.fileno(), TCSAFLUSH, stash)
, you don't have to learn what all those fiddly bits mean.
On both platforms, mixing console I/O and raw terminal mode is painful. You definitely can't use the sys.stdin
buffer if you've ever done any console/raw reading; you can only use sys.stdin.buffer.raw
. You could always replace readline
by reading character by character until you get a newline… but if the user tries to edit his entry by using backspace, arrows, emacs-style command keys, etc., you're going to get all those as raw keypresses, which you don't want to deal with.
Can not multi action same name and same parameter
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(int id)
{
return View();
}
althought int id is not used
CREATE ROLE blog WITH
LOGIN
SUPERUSER
INHERIT
CREATEDB
CREATEROLE
REPLICATION;
COMMENT ON ROLE blog IS 'Test';
A static method belongs to the class and a non-static method belongs to an object of a class. I am giving one example how it creates difference between outputs.
public class DifferenceBetweenStaticAndNonStatic {
static int count = 0;
private int count1 = 0;
public DifferenceBetweenStaticAndNonStatic(){
count1 = count1+1;
}
public int getCount1() {
return count1;
}
public void setCount1(int count1) {
this.count1 = count1;
}
public static int countStaticPosition() {
count = count+1;
return count;
/*
* one can not use non static variables in static method.so if we will
* return count1 it will give compilation error. return count1;
*/
}
}
public class StaticNonStaticCheck {
public static void main(String[] args){
for(int i=0;i<4;i++) {
DifferenceBetweenStaticAndNonStatic p =new DifferenceBetweenStaticAndNonStatic();
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.count);
System.out.println("static count position is " +p.getCount1());
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.countStaticPosition());
System.out.println("next case: ");
System.out.println(" ");
}
}
}
Now output will be:::
static count position is 0
static count position is 1
static count position is 1
next case:
static count position is 1
static count position is 1
static count position is 2
next case:
static count position is 2
static count position is 1
static count position is 3
next case:
Also a good example.....
struct point{int x,y;};
typedef struct point point_t;
typedef struct
{
struct point ne,se,sw,nw;
}rect_t;
rect_t temp;
int main()
{
//rotate
RotateRect(&temp);
return 0;
}
void RotateRect(rect_t *givenRect)
{
point_t temp_point;
/*Copy struct data from struct to struct within a struct*/
temp_point = givenRect->sw;
givenRect->sw = givenRect->se;
givenRect->se = givenRect->ne;
givenRect->ne = givenRect->nw;
givenRect->nw = temp_point;
}
Both do the same on all browsers, AFAIK. Checked on Chrome and Firefox, both append display:none
to the style
attribute of the element.
You can use the change command to replace the entire line, and the -i
flag to make the changes in-place. For example, using GNU sed:
sed -i '/TEXT_TO_BE_REPLACED/c\This line is removed by the admin.' /tmp/foo
If it isn't I could see things heading that way.
I'm working on redoing the website for the company I work for and the designer they hired used a 960px width layout. There is also a 960px grid system that seems to be getting quite popular (http://960.gs/).
I've been out of web stuff for a few years but from what I've read catching up on things it seems 960/980 is about right. For mobile ~320px sticks in my mind, by which 960 is divisible. 960 is also evenly divisible by 2, 3, 4, 5, and 6.
XmlTextWriter xmlw = new XmlTextWriter(@"C:\WINDOWS\Temp\exm.xml",System.Text.Encoding.UTF8);
xmlw.WriteStartDocument();
xmlw.WriteStartElement("examtimes");
xmlw.WriteStartElement("Starttime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Changetime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Endtime");
xmlw.WriteString(DateTime.Now.AddHours(1).ToString());
xmlw.WriteEndElement();
xmlw.WriteEndElement();
xmlw.WriteEndDocument();
xmlw.Close();
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\WINDOWS\Temp\exm.xml");
XmlNode root = doc.DocumentElement["Starttime"];
root.FirstChild.InnerText = "First";
XmlNode root1 = doc.DocumentElement["Changetime"];
root1.FirstChild.InnerText = "Second";
doc.Save(@"C:\WINDOWS\Temp\exm.xml");
Try this. It's C# code.
Open Task Manager and Kill both of these processes. They will autostart back up. Then try debugging your project again.
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
There's a hook called useLocation in react-router v5, no need for HOC or other stuff, it's very succinctly and convenient.
import { useLocation } from 'react-router-dom';
const ExampleComponent: React.FC = () => {
const location = useLocation();
return (
<Router basename='/app'>
<main>
<AppBar handleMenuIcon={this.handleMenuIcon} title={location.pathname} />
</main>
</Router>
);
}
"C:\Program Files (x86)\ffmpegX86shared\bin\ffmpeg.exe" -y -i "C:\testfile.ts" -an -vcodec libx264 -g 75 -keyint_min 12 -vb 4000k -vprofile high -level 40 -s 1920x1080 -y -threads 0 -r 25 "C:\testfile.h264"
The above worked for me on a Windows machine using a FFmpeg Win32 shared build by Kyle Schwarz. The build was compiled on: Feb 22 2013, at: 01:09:53
Note that -an defines that audio should be skipped.
Possible solutions:
Use nginx on the server as a proxy that will listen to port A and multiplex to port B or C.
If you use AWS you can use the load balancer to redirect the request to specific port based on the host.
If you support IE, for versions of Internet Explorer 8 and above, this:
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />
Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.
If you separate with semi-colon, it sets compatibility levels for different versions. For example:
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />
Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:
<meta http-equiv="X-UA-Compatible" content="IE=8" />
This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
For this:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
It forces the browser the render at whatever the most recent version's standards are.
For more information, there is plenty to read about on MSDN,
It's an old question, but here are some comments...
I used the following code to listen to changes to an array.
/* @arr array you want to listen to
@callback function that will be called on any change inside array
*/
function listenChangesinArray(arr,callback){
// Add more methods here if you want to listen to them
['pop','push','reverse','shift','unshift','splice','sort'].forEach((m)=>{
arr[m] = function(){
var res = Array.prototype[m].apply(arr, arguments); // call normal behaviour
callback.apply(arr, arguments); // finally call the callback supplied
return res;
}
});
}
Hope this was useful :)
Don't really know how they compare for speed, but the first one looks like the right idea for scaling to really big JSON data, since it parses only a small chunk at a time so they don't need to hold all the data in memory at once (This can be faster or slower depending on the library/use case)
I think you mean to update it back to the OLD
password, when the NEW one is not supplied.
DROP TRIGGER IF EXISTS upd_user;
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '') THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
However, this means a user can never blank out a password.
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
check More than one Permission and Request if Not Granted
public void checkPermissions(){
if(ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED){
//Do_SOme_Operation();
}else{
requestStoragePermission();
}
}
public void requestStoragePermission(){
ActivityCompat.requestPermissions(this
,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},1234);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 1234:if(grantResults[0]==PackageManager.PERMISSION_GRANTED && grantResults[1]==PackageManager.PERMISSION_GRANTED){
// Do_SOme_Operation();
}
default:super.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
}
You can make responsive grid of squares with verticaly and horizontaly centered content only with CSS. I will explain how in a step by step process but first here are 2 demos of what you can achieve :
Now let's see how to make these fancy responsive squares!
The trick for keeping elements square (or whatever other aspect ratio) is to use percent padding-bottom
.
Side note: you can use top padding too or top/bottom margin but the background of the element won't display.
As top padding is calculated according to the width of the parent element (See MDN for reference), the height of the element will change according to its width. You can now Keep its aspect ratio according to its width.
At this point you can code :
HTML :
<div></div>
CSS
div {
width: 30%;
padding-bottom: 30%; /* = width for a square aspect ratio */
}
Here is a simple layout example of 3*3 squares grid using the code above.
With this technique, you can make any other aspect ratio, here is a table giving the values of bottom padding according to the aspect ratio and a 30% width.
Aspect ratio | padding-bottom | for 30% width
------------------------------------------------
1:1 | = width | 30%
1:2 | width x 2 | 60%
2:1 | width x 0.5 | 15%
4:3 | width x 0.75 | 22.5%
16:9 | width x 0.5625 | 16.875%
As you can't add content directly inside the squares (it would expand their height and squares wouldn't be squares anymore) you need to create child elements (for this example I am using divs) inside them with position: absolute;
and put the content inside them. This will take the content out of the flow and keep the size of the square.
Don't forget to add position:relative;
on the parent divs so the absolute children are positioned/sized relatively to their parent.
Let's add some content to our 3x3 grid of squares :
HTML :
<div class="square">
<div class="content">
.. CONTENT HERE ..
</div>
</div>
... and so on 9 times for 9 squares ...
CSS :
.square {
float:left;
position: relative;
width: 30%;
padding-bottom: 30%; /* = width for a 1:1 aspect ratio */
margin:1.66%;
overflow:hidden;
}
.content {
position:absolute;
height:80%; /* = 100% - 2*10% padding */
width:90%; /* = 100% - 2*5% padding */
padding: 10% 5%;
}
RESULT <-- with some formatting to make it pretty!
Horizontally :
This is pretty easy, you just need to add text-align:center
to .content
.
RESULT
Vertical alignment
This becomes serious! The trick is to use
display:table;
/* and */
display:table-cell;
vertical-align:middle;
but we can't use display:table;
on .square
or .content
divs because it conflicts with position:absolute;
so we need to create two children inside .content
divs. Our code will be updated as follow :
HTML :
<div class="square">
<div class="content">
<div class="table">
<div class="table-cell">
... CONTENT HERE ...
</div>
</div>
</div>
</div>
... and so on 9 times for 9 squares ...
CSS :
.square {
float:left;
position: relative;
width: 30%;
padding-bottom : 30%; /* = width for a 1:1 aspect ratio */
margin:1.66%;
overflow:hidden;
}
.content {
position:absolute;
height:80%; /* = 100% - 2*10% padding */
width:90%; /* = 100% - 2*5% padding */
padding: 10% 5%;
}
.table{
display:table;
height:100%;
width:100%;
}
.table-cell{
display:table-cell;
vertical-align:middle;
height:100%;
width:100%;
}
We have now finished and we can take a look at the result here :
The INSERT INTO Statement
The INSERT INTO statement is used to insert a new row in a table.
SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
The simplest Angular jqLite version.
JS:
.directive('cOnChange', function() {
'use strict';
return {
restrict: "A",
scope : {
cOnChange: '&'
},
link: function (scope, element) {
element.on('change', function () {
scope.cOnChange();
});
}
};
});
HTML:
<input type="file" data-c-on-change="your.functionName()">
Hamidreza's solution almost worked for me.
I noticed from experimentation that a simple tap usually has 2-5 action move events. Checking the time between action down and up was simpler and behaved more like what I expected.
private class CheckForClickTouchLister implements View.OnTouchListener {
private final static long MAX_TOUCH_DURATION = 100;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
m_DownTime = event.getEventTime(); //init time
break;
case MotionEvent.ACTION_UP:
if(event.getEventTime() - m_DownTime <= MAX_TOUCH_DURATION)
//On click action
break;
default:
break; //No-Op
}
return false;
}
It should be noted as well that this will of course only find all those subclasses that exist on your current classpath. Presumably this is OK for what you are currently looking at, and chances are you did consider this, but if you have at any point released a non-final
class into the wild (for varying levels of "wild") then it is entirely feasible that someone else has written their own subclass that you will not know about.
Thus if you happened to be wanting to see all subclasses because you want to make a change and are going to see how it affects subclasses' behaviour - then bear in mind the subclasses that you can't see. Ideally all of your non-private methods, and the class itself should be well-documented; make changes according to this documentation without changing the semantics of methods/non-private fields and your changes should be backwards-compatible, for any subclass that followed your definition of the superclass at least.
Is there a way to get it via $event->getComposer()->getRepositoryManager()->getAllPackages()
0 values of basic types (1)(2)map to false
.
Other values map to true
.
This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.
It's a common error to assume that as function return values, false
indicates failure. But in particular from main
it's false
that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.
There's no need to cast to bool
for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x
, works nicely. One can read !!
as a “convert to bool
” operator, much as -->
can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)
1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false
; any other value is converted to true
. For direct-initialization (8.5), a prvalue of type std::nullptr_t
can be converted to a prvalue of type bool
; the resulting value is false
.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool
, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”
Do you only want the pixels or the whole image (including headers) as an byte array?
For pixels: Use the CopyPixels
method on Bitmap. Something like:
var bitmap = new BitmapImage(uri);
//Pixel array
byte[] pixels = new byte[width * height * 4]; //account for stride if necessary and whether the image is 32 bit, 16 bit etc.
bitmap.CopyPixels(..size, pixels, fullStride, 0);
if you know the spect ratio you can use padding-bottom with percentage to set the hight depending on with of the diff.
<div>
<div style="padding-bottom: 33%;">
i have 33% height of my parents width
</div>
</div>
CSS:
.container div{
width: 33.33%;
float: left;
height: 100px ;}
Clear floats after the columns
.container:after {
content: "";
display: table;
clear: both;}
If you're running Python 3.4+, you can use the pathlib
module. The Path.glob()
method supports the **
pattern, which means “this directory and all subdirectories, recursively”. It returns a generator yielding Path
objects for all matching files.
from pathlib import Path
configfiles = Path("C:/Users/sam/Desktop/file1/").glob("**/*.txt")
See: http://googletesting.blogspot.com/2007/02/tott-naming-unit-tests-responsibly.html
For test method names, I personally find using verbose and self-documented names very useful (alongside Javadoc comments that further explain what the test is doing).
This was happening in the production environment for me.
rm /vendor/bundle
then
bundle install --deployment
resolved the issue.
I think you're looking for npm prune
npm prune [<name> [<name ...]]
This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.
Extraneous packages are packages that are not listed on the parent package's dependencies list.
See the docs: https://docs.npmjs.com/cli/prune
The easiest thing is to run the program, open the task manager, right-click the process and select properties, here is the full address
First, your HTML markup looks like this:
<video id="awesome_video" src="first_video.mp4" autoplay />
Second, your JavaScript code will look like this:
<script type="text/javascript">
var index = 1,
playlist = ['first_video.mp4', 'second_video.mp4', 'third_video.mp4'],
video = document.getElementById('awesome_video');
video.addEventListener('ended', rotate_video, false);
function rotate_video() {
video.setAttribute('src', playlist[index]);
video.load();
index++;
if (index >= playlist.length) { index = 0; }
}
</script>
And last but not least, your CSS:
#awesome_video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
This will create a video element on your page that starts playing the first video right away, then iterates through the playlist defined by the JavaScript variable. Your mileage with the CSS may vary depending on the CSS for the rest of the site, but 100% width/height should do it on a basic page.
The answer to that can be quite broad.
Essentially, the major difference for me that usually influences my decisions on which to use is that with a SQLDataReader, you are "streaming" data from the database. With a SQLDataAdapter, you are extracting the data from the database into an object that can itself be queried further, as well as performing CRUD operations on.
Obviously with a stream of data SQLDataReader is MUCH faster, but you can only process one record at a time. With a SQLDataAdapter, you have a complete collection of the matching rows to your query from the database to work with/pass through your code.
WARNING: If you are using a SQLDataReader, ALWAYS, ALWAYS, ALWAYS make sure that you write proper code to close the connection since you are keeping the connection open with the SQLDataReader. Failure to do this, or proper error handling to close the connection in case of an error in processing the results will CRIPPLE your application with connection leaks.
Pardon my VB, but this is the minimum amount of code you should have when using a SqlDataReader:
Using cn As New SqlConnection("..."), _
cmd As New SqlCommand("...", cn)
cn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
''# ...
End While
End Using
End Using
equivalent C#:
using (var cn = new SqlConnection("..."))
using (var cmd = new SqlCommand("..."))
{
cn.Open();
using(var rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
//...
}
}
}
It's not really a performance question at all, since arrays and objects work very differently (or are supposed to, at least). Arrays have a continuous index 0..n
, while objects map arbitrary keys to arbitrary values. If you want to supply specific keys, the only choice is an object. If you don't care about the keys, an array it is.
If you try to set arbitrary (numeric) keys on an array, you really have a performance loss, since behaviourally the array will fill in all indexes in-between:
> foo = [];
[]
> foo[100] = 'a';
"a"
> foo
[undefined, undefined, undefined, ..., "a"]
(Note that the array does not actually contain 99 undefined
values, but it will behave this way since you're [supposed to be] iterating the array at some point.)
The literals for both options should make it very clear how they can be used:
var arr = ['foo', 'bar', 'baz']; // no keys, not even the option for it
var obj = { foo : 'bar', baz : 42 }; // associative by its very nature
Notepad++ provides 2 types of features:
Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.
To do that, you just need to change a setting.
Settings
> Preferences...
> Auto-completion
Enable Auto-completion on each input
Function completion
and not Word completion
Function parameter hint on input
(if you have this option)On version 6.5.5 of Notepad++, I have this setting
Some documentation about auto-completion is available in Notepad++ Wiki.
The parameter has this syntax:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
So your example of '1.2-2'
means:
Also, make sure you have no files that accidentally try to inherit or define the same (partial) class as other files. Note that these files can seem unrelated to the files where the error actually appeared!
In Oracle 12c and above, we have two types of databases:
If you want to create an user, you have two possibilities:
You can create a "container user" aka "common user".
Common users belong to CBDs as well as to current and future PDBs. It means they can perform operations in Container DBs or Pluggable DBs according to assigned privileges.
create user c##username identified by password;
You can create a "pluggable user" aka "local user".
Local users belong only to a single PDB. These users may be given administrative privileges, but only for that PDB inside which they exist. For that, you should connect to pluggable datable like that:
alter session set container = nameofyourpluggabledatabase;
and there, you can create user like usually:
create user username identified by password;
Don't forget to specify the tablespace(s) to use, it can be useful during import/export of your DBs. See this for more information about it https://docs.oracle.com/database/121/SQLRF/statements_8003.htm#SQLRF01503
just use onkeypress event like below:
<input type="text" name="onlyalphabet" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
You can do request.env['REQUEST_URI']
to see the full requested URI.. it will output something like below
http://localhost:3000/client/1/users/1?name=test
You don't need to use GROUP BY but using it won't change the outcome. Just add an ORDER BY line at the end to sort your results.
SELECT player_name, player_salary, SUM(player_salary*1.1) AS NewSalary
FROM players
GROUP BY player_salary, player_name;
ORDER BY SUM(player_salary*1.1) DESC
Maven is a Framework, Ant is a Toolbox
Maven is a pre-built road car, whereas Ant is a set of car parts. With Ant you have to build your own car, but at least if you need to do any off-road driving you can build the right type of car.
To put it another way, Maven is a framework whereas Ant is a toolbox. If you're content with working within the bounds of the framework then Maven will do just fine. The problem for me was that I kept bumping into the bounds of the framework and it wouldn't let me out.
XML Verbosity
tobrien is a guy who knows a lot about Maven and I think he provided a very good, honest comparison of the two products. He compared a simple Maven pom.xml with a simple Ant build file and he made mention of how Maven projects can become more complex. I think that its worth taking a look at a comparison of a couple of files that you are more likely to see in a simple real-world project. The files below represent a single module in a multi-module build.
First, the Maven file:
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-4_0_0.xsd">
<parent>
<groupId>com.mycompany</groupId>
<artifactId>app-parent</artifactId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>persist</artifactId>
<name>Persistence Layer</name>
<dependencies>
<dependency>
<groupId>com.mycompany</groupId>
<artifactId>common</artifactId>
<scope>compile</scope>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.mycompany</groupId>
<artifactId>domain</artifactId>
<scope>provided</scope>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>${hibernate.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons-lang.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.2.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${commons-dbcp.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc</artifactId>
<version>${oracle-jdbc.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>${easymock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
And the equivalent Ant file:
<project name="persist" >
<import file="../build/common-build.xml" />
<path id="compile.classpath.main">
<pathelement location="${common.jar}" />
<pathelement location="${domain.jar}" />
<pathelement location="${hibernate.jar}" />
<pathelement location="${commons-lang.jar}" />
<pathelement location="${spring.jar}" />
</path>
<path id="compile.classpath.test">
<pathelement location="${classes.dir.main}" />
<pathelement location="${testng.jar}" />
<pathelement location="${dbunit.jar}" />
<pathelement location="${easymock.jar}" />
<pathelement location="${commons-dbcp.jar}" />
<pathelement location="${oracle-jdbc.jar}" />
<path refid="compile.classpath.main" />
</path>
<path id="runtime.classpath.test">
<pathelement location="${classes.dir.test}" />
<path refid="compile.classpath.test" />
</path>
</project>
tobrien used his example to show that Maven has built-in conventions but that doesn't necessarily mean that you end up writing less XML. I have found the opposite to be true. The pom.xml is 3 times longer than the build.xml and that is without straying from the conventions. In fact, my Maven example is shown without an extra 54 lines that were required to configure plugins. That pom.xml is for a simple project. The XML really starts to grow significantly when you start adding in extra requirements, which is not out of the ordinary for many projects.
But you have to tell Ant what to do
My Ant example above is not complete of course. We still have to define the targets used to clean, compile, test etc. These are defined in a common build file that is imported by all modules in the multi-module project. Which leads me to the point about how all this stuff has to be explicitly written in Ant whereas it is declarative in Maven.
Its true, it would save me time if I didn't have to explicitly write these Ant targets. But how much time? The common build file I use now is one that I wrote 5 years ago with only slight refinements since then. After my 2 year experiment with Maven, I pulled the old Ant build file out of the closet, dusted it off and put it back to work. For me, the cost of having to explicitly tell Ant what to do has added up to less than a week over a period of 5 years.
Complexity
The next major difference I'd like to mention is that of complexity and the real-world effect it has. Maven was built with the intention of reducing the workload of developers tasked with creating and managing build processes. In order to do this it has to be complex. Unfortunately that complexity tends to negate their intended goal.
When compared with Ant, the build guy on a Maven project will spend more time:
In contrast:
Familiarity
Another difference is that of familiarity. New developers always require time to get up to speed. Familiarity with existing products helps in that regard and Maven supporters rightly claim that this is a benefit of Maven. Of course, the flexibility of Ant means that you can create whatever conventions you like. So the convention I use is to put my source files in a directory name src/main/java. My compiled classes go into a directory named target/classes. Sounds familiar doesn't it.
I like the directory structure used by Maven. I think it makes sense. Also their build lifecycle. So I use the same conventions in my Ant builds. Not just because it makes sense but because it will be familiar to anyone who has used Maven before.
extracted_url = url[url.rfind("/")+1:];
In mysql server 8.0, on Windows, the location is C:\ProgramData\MySQL\MySQL Server 8.0\Data
grep '^..' my_file
example
THIS
IS
THE
FILE
EOF_MYFILE
it gives as output only lines with at least 2 characters.
THIS
IS
THE
FILE
EOF_MYFILE
See also the results with grep '^' my_file
outputs
THIS
IS
THE
FILE
EOF_MYFILE
and also with grep '^.' my_file
outputs
THIS
IS
THE
FILE
EOF_MYFILE
ArrayList<String> newlyAddedTypes=new ArrayList<String>();
.....
newlyAddedTypes.add("test1");
newlyAddedTypes.add("test1");
newlyAddedTypes.add("test2");
if(newlyAddedTypes.contain("test"){
//called here
}
else{
}
In my part my sql hanged up when I tried to close it while endlessly running. So what I did is I open my task manager and end task my sql query. This stop my sql and restarted it.
When using java 8, you may take advantage of stream API and simplify code to
return (YourEntityClass) entityManager.createQuery()
....
.getResultList()
.stream().findFirst();
That will give you java.util.Optional
If you prefer null instead, all you need is
...
.getResultList()
.stream().findFirst().orElse(null);
Macro to find endiannes
#define ENDIANNES() ((1 && 1 == 0) ? printf("Big-Endian"):printf("Little-Endian"))
or
#include <stdio.h>
#define ENDIAN() { \
volatile unsigned long ul = 1;\
volatile unsigned char *p;\
p = (volatile unsigned char *)&ul;\
if (*p == 1)\
puts("Little endian.");\
else if (*(p+(sizeof(unsigned long)-1)) == 1)\
puts("Big endian.");\
else puts("Unknown endian.");\
}
int main(void)
{
ENDIAN();
return 0;
}
This could be due to the fact that another instance of mysqd is already running in your mac-book-pro (MacOs-10). It's next to impossible to kill/pkill mysqld or ....I tried that route many times, with out any success. Finally the following worked for me :
launchctl unload -w /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist
wait a few minutes and check with
ps -ef|grep mysqld
It should be gone!
Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.
As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs
e.g.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
In case you need further info for your log/audit you can OUTPUT clause: This way, not only you keep the number of rows affected, but also what records.
As an example of the Output Clause during inserts: SQL Server list of insert identities
DECLARE @InsertedIDs table(ID int);
INSERT INTO YourTable
OUTPUT INSERTED.ID
INTO @InsertedIDs
SELECT ...
HTH
Couldn't this simply be done by getting actual position of the mouse pointer then calculating and compensating sprite/scene mouse actions based off this compensation?
For instance you need the mouse pointer to be bottom center, but it sits top left; hide the cursor, use a shifted cursor image. Shift the cursor movement and map mouse input to match re-positioned cursor sprite (or 'control') clicks When/if bounds are hit, recalculate. If/when the cursor actually hits the point you want it to be, remove compensation.
Disclaimer, not a game developer.
You need to use Regular Expression For Website URL it is
var urlPattern = /(http|ftp|https)://[\w-]+(.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/
Use this Expression as in example
var regex = new RegExp(urlPattern ); var t = 'www.google.com';
var res = t.match(regex /g);
For You have to pass your web page as string to this javascript in variable t and get array
From Collections#synchronizedList(List)
javadoc
Returns a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list ... It is imperative that the user manually synchronize on the returned list when iterating over it. Failure to follow this advice may result in non-deterministic behavior.
At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.
$mail->ClearReplyTos();
$mail->addReplyTo([email protected], 'EXAMPLE');
You cannot disable linker warning 4099, as said @John Weldon.
You should rebuild library with some project configuration changes. You have several options:
Using file:///// just doesn't work if security settings are set to even a moderate level.
If you just want users to be able to download/view files* located on a network or share you can set up a Virtual Directory in IIS. On the Properties tab make sure the "A share located on another computer" is selected and the "Connect as..." is an account that can see the network location.
Link to the virtual directory from your webpage (e.g. http://yoursite/yourvirtualdir/) and this will open up a view of the directory in the web browser.
*You can allow write permissions on the virtual directory to allow users to add files but not tried it and assume network permissions would override this setting.
This problem comes from a strange quirk within Office/Windows.
After developing the same piece of VBA code and running it hundreds of times (literally) over the last couple days I ran into this problem just now. The only thing that has been different is that just prior to experiencing this perplexing problem I accidentally ended the execution of the VBA code with an unorthodox method.
I cleaned out all temp files, rebooted, etc... When I ran the code again after all of this I still got the issue - before I entered the first loop. It makes sense that "press "Debug" button in the popup, then press twice [Ctrl+Break] and after this can continue without stops" because something in the combination of Office/Windows has not released the execution. It is stuck.
The redundant Ctrl+Break action probably resolves the lingering execution.
You should set responseType: ResponseContentType.Blob
in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.
Here is an working example:
Create image.service.ts
and put following code:
Angular 4:
getImage(imageUrl: string): Observable<File> {
return this.http
.get(imageUrl, { responseType: ResponseContentType.Blob })
.map((res: Response) => res.blob());
}
Angular 5+:
getImage(imageUrl: string): Observable<Blob> {
return this.httpClient.get(imageUrl, { responseType: 'blob' });
}
Important: Since Angular 5+ you should use the new HttpClient
.
The new HttpClient
returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'
. Read more about that here.
Now you need to create some function in your image.component.ts
to get image and show it in html.
For creating an image from Blob you need to use JavaScript's FileReader
.
Here is function which creates new FileReader
and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:
imageToShow: any;
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageToShow = reader.result;
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
Now you should use your created ImageService
to get image from api. You should to subscribe to data and give this data to createImageFromBlob
-function. Here is an example function:
getImageFromService() {
this.isImageLoading = true;
this.imageService.getImage(yourImageUrl).subscribe(data => {
this.createImageFromBlob(data);
this.isImageLoading = false;
}, error => {
this.isImageLoading = false;
console.log(error);
});
}
Now you can use your imageToShow
-variable in HTML template like this:
<img [src]="imageToShow"
alt="Place image title"
*ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
<img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>
I hope this description is clear to understand and you can use it in your project.
See the working example for Angular 5+ here.
To find the point where to add the -lm in Eclipse-IDE is really horrible, so it took me some time.
If someone else also uses Edlipse, here's the way how to add the command:
Project -> Properties -> C/C++ Build -> Settings -> GCC C Linker -> Miscelleaneous -> Linker flags: in this field add the command -lm
I got this error when my service declaration was inside a non-invoked function (IIFE). The last line below did NOT have the extra () to run and define the service.
(function() {
"use strict";
angular.module("reviewService", [])
.service("reviewService", reviewService);
function reviewService($http, $q, $log) {
//
}
}());
Disclaimer: I've written fast-xml-parser
Fast XML Parser can help to convert XML to JSON and vice versa. Here is the example;
var options = {
attributeNamePrefix : "@_",
attrNodeName: "attr", //default is 'false'
textNodeName : "#text",
ignoreAttributes : true,
ignoreNameSpace : false,
allowBooleanAttributes : false,
parseNodeValue : true,
parseAttributeValue : false,
trimValues: true,
decodeHTMLchar: false,
cdataTagName: "__cdata", //default is 'false'
cdataPositionChar: "\\c",
};
if(parser.validate(xmlData)=== true){//optional
var jsonObj = parser.parse(xmlData,options);
}
If you want to parse JSON or JS object into XML then
//default options need not to set
var defaultOptions = {
attributeNamePrefix : "@_",
attrNodeName: "@", //default is false
textNodeName : "#text",
ignoreAttributes : true,
encodeHTMLchar: false,
cdataTagName: "__cdata", //default is false
cdataPositionChar: "\\c",
format: false,
indentBy: " ",
supressEmptyNode: false
};
var parser = new parser.j2xParser(defaultOptions);
var xml = parser.parse(json_or_js_obj);
I got this error on Azure Git, and this solves the problem:
git fetch
git pull
git push --no-verify
For regex, I first look at this web site: RegExLib.com
This worked for me.
First of all give the view controller in your storyboard a Storyboard ID inside the identity inspector. Then use the following example code (ensuring the class, storyboard name and story board ID match those that you are using):
let viewController:
UIViewController = UIStoryboard(
name: "Main", bundle: nil
).instantiateViewControllerWithIdentifier("ViewController") as UIViewController
// .instantiatViewControllerWithIdentifier() returns AnyObject!
// this must be downcast to utilize it
self.presentViewController(viewController, animated: false, completion: nil)
For more details see http://sketchytech.blogspot.com/2012/11/instantiate-view-controller-using.html best wishes
curl is a command in linux (and a library in php). Curl typically makes an HTTP request.
What you really want to do is make an HTTP (or XHR) request from javascript.
Using this vocab you'll find a bunch of examples, for starters: Sending authorization headers with jquery and ajax
Essentially you will want to call $.ajax
with a few options for the header, etc.
$.ajax({
url: 'https://api.wit.ai/message?v=20140826&q=',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
}, success: function(data){
alert(data);
//process the JSON data etc
}
})
Please store your JSON file with the .js extension and make sure that your JSON should be in same directory.
All has great answer on the question, and yes this is only applicable when running it on the current directory not unless you include the absolute path. See my samples below.
Also, the (dot-slash) made sense to me when I've the command on the child folder tmp2 (/tmp/tmp2) and it uses (double dot-slash).
SAMPLE:
[fifiip-172-31-17-12 tmp]$ ./StackO.sh
Hello Stack Overflow
[fifi@ip-172-31-17-12 tmp]$ /tmp/StackO.sh
Hello Stack Overflow
[fifi@ip-172-31-17-12 tmp]$ mkdir tmp2
[fifi@ip-172-31-17-12 tmp]$ cd tmp2/
[fifi@ip-172-31-17-12 tmp2]$ ../StackO.sh
Hello Stack Overflow
This is very much implementation specific, but the general idea is to allow providers to issue short term access tokens with long term refresh tokens. Why?
For swift 4.2
--
//MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1 //return number of sections in collection view
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10 //return number of rows in section
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
configureCell(cell: cell, forItemAtIndexPath: indexPath)
return cell //return your cell
}
func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
cell.backgroundColor = UIColor.black
//Customise your cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", for: indexPath as IndexPath) as UICollectionReusableView
return view
}
//MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// When user selects the cell
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
// When user deselects the cell
}
For the accepted answer when you try to hide any view inside stack view, the constraint works not correct.
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x618000086e50 UIView:0x7fc11c4051c0.height == 120 (active)>",
"<NSLayoutConstraint:0x610000084fb0 'UISV-hiding' UIView:0x7fc11c4051c0.height == 0 (active)>"
)
Reason is when hide the view
in stackView
it will set the height to 0 to animate it.
Solution change the constraint priority
as below.
import UIKit
class ViewController: UIViewController {
let stackView = UIStackView()
let a = UIView()
let b = UIView()
override func viewDidLoad() {
super.viewDidLoad()
a.backgroundColor = UIColor.red
a.widthAnchor.constraint(equalToConstant: 200).isActive = true
let aHeight = a.heightAnchor.constraint(equalToConstant: 120)
aHeight.isActive = true
aHeight.priority = 999
let bHeight = b.heightAnchor.constraint(equalToConstant: 120)
bHeight.isActive = true
bHeight.priority = 999
b.backgroundColor = UIColor.green
b.widthAnchor.constraint(equalToConstant: 200).isActive = true
view.addSubview(stackView)
stackView.backgroundColor = UIColor.blue
stackView.addArrangedSubview(a)
stackView.addArrangedSubview(b)
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.translatesAutoresizingMaskIntoConstraints = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Just add a button in xib file or storyboard and add connect this action.
@IBAction func test(_ sender: Any) {
a.isHidden = !a.isHidden
}
}
this works fine, but file name does not display anymore.
$(document).ready(function(){ $("img.attach2").click(function(){ $("input.attach1").click(); return false; }); });
The simple way to create Current TimeStamp. like below,
func generateCurrentTimeStamp () -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy_MM_dd_hh_mm_ss"
return (formatter.string(from: Date()) as NSString) as String
}
In your case you can use __FILE__
variable !
It should help.
It is one of predefined.
Read more about predefined constants in PHP http://php.net/manual/en/language.constants.predefined.php
Have you tried height: auto;
on your .container
div?
Here is a fiddle, if you change img height, container height will adjust to it.
EDIT
So if you "can't" change the inline min-height
, you can overwrite the inline style with an !important
parameter. It's not the cleanest way, but it solves your problem.
add to your .container
class this line
min-height:0px !important;
I've updated my fiddle to give you an example.
For me, the answers above did not work with matplotlib.__version__ = 1.4.3
on Win7. So, if we are only interested in the image itself (i.e., if we don't need annotations, axis, ticks, title, ylabel etc), then it's better to simply save the numpy array as image instead of savefig
.
from pylab import *
ax = subplot(111)
ax.imshow(some_image_numpyarray)
imsave('test.tif', some_image_numpyarray)
# or, if the image came from tiff or png etc
RGBbuffer = ax.get_images()[0].get_array()
imsave('test.tif', RGBbuffer)
Also, using opencv drawing functions (cv2.line, cv2.polylines), we can do some drawings directly on the numpy array. http://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html
Here is the code for you`r class . but this also contains lot of refactoring. Please add a for each rather than for. cheers :)
static int isLeft(ArrayList<String> left, ArrayList<String> right)
{
int f = 0;
for (int i = 0; i < left.size(); i++) {
for (int j = 0; j < right.size(); j++)
{
if (left.get(i).charAt(0) == right.get(j).charAt(0)) {
System.out.println("Grammar is left recursive");
f = 1;
}
}
}
return f;
}
public static void main(String[] args) {
// TODO code application logic here
ArrayList<String> left = new ArrayList<String>();
ArrayList<String> right = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("enter no of prod");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("enter left prod");
String leftText = sc.next();
left.add(leftText);
System.out.println("enter right prod");
String rightText = sc.next();
right.add(rightText);
}
System.out.println("the productions are");
for (int i = 0; i < n; i++) {
System.out.println(left.get(i) + "->" + right.get(i));
}
int flag;
flag = isLeft(left, right);
if (flag == 1) {
System.out.println("Removing left recursion");
} else {
System.out.println("No left recursion");
}
}
Late to this one, but I just discovered an alternative way of doing it:
On your template,
<a (click)="navigateAssociates()">Associates</a>
And on your component.ts, you can use serializeUrl
to convert the route into a string, which can be used with window.open()
navigateAssociates() {
const url = this.router.serializeUrl(
this.router.createUrlTree(['/page1'])
);
window.open(url, '_blank');
}
This is good and efficient approach as per time complexity prospect. Once it will get a true condition , it will not check any other after this. In multiple If , it will check each and condition.
<c:choose>
<c:when test="${condtion1}">
do something condtion1
</c:when>
<c:when test="${condtion2}">
do something condtion2
</c:when>
......
......
......
.......
<c:when test="${condtionN}">
do something condtionn N
</c:when>
<c:otherwise>
do this w
</c:otherwise>
</c:choose>
This works for me:
function refreshPage(){
window.location.reload();
}
<button type="submit" onClick="refreshPage()">Refresh Button</button>
I've spend more than a day trying to make JMX to work from outside localhost. It seems that SUN/Oracle failed to provide a good documentation on this.
Be sure that the following command returns you a real IP or HOSTNAME. If it does return something like 127.0.0.1, 127.0.1.1 or localhost it will not work and you will have to update /etc/hosts
file.
hostname -i
Here is the command needed to enable JMX even from outside
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.port=1100
-Djava.rmi.server.hostname=myserver.example.com
Where as you assumed, myserver.example.com must match what hostname -i
returns.
Obviously, you need to be sure that the firewall does not block you, but I'm almost sure that this is not your problem, the problem being the last parameter that is not documented.
You don't need to use arrays.
JSON values can be arrays, objects, or primitives (numbers or strings).
You can write JSON like this:
{
"stuff": {
"onetype": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"othertype": {"id":2,"company":"ACME"}
},
"otherstuff": {
"thing": [[1,42],[2,2]]
}
}
You can use it like this:
obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1] //thing is a nested array or a 2-by-2 matrix.
//I'm not sure whether you intended to do that.
Since eggyal didn't provided his comment as answer after he gave right advice in a comment - i am posting it here: In my case I had to install module php-mysql
. See comments under the question for details.
url-pattern
is used in web.xml
to map your servlet
to specific URL. Please see below xml code, similar code you may find in your web.xml
configuration file.
<servlet>
<servlet-name>AddPhotoServlet</servlet-name> //servlet name
<servlet-class>upload.AddPhotoServlet</servlet-class> //servlet class
</servlet>
<servlet-mapping>
<servlet-name>AddPhotoServlet</servlet-name> //servlet name
<url-pattern>/AddPhotoServlet</url-pattern> //how it should appear
</servlet-mapping>
If you change url-pattern
of AddPhotoServlet
from /AddPhotoServlet
to /MyUrl
. Then, AddPhotoServlet
servlet can be accessible by using /MyUrl
. Good for the security reason, where you want to hide your actual page URL.
Java Servlet url-pattern
Specification:
- A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
- A string beginning with a '*.' prefix is used as an extension mapping.
- A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
- All other strings are used for exact matches only.
Reference : Java Servlet Specification
You may also read this Basics of Java Servlet
I ended up doing this by exporting a frozen object with anonymous getter functions, rather than the constants themselves. This reduces the risk of nasty bugs introduced due to a simple typo of the const name, as a runtime error will be thrown in case of a typo. Here's a full example that also uses ES6 Symbols for the constants, ensuring uniqueness, and ES6 arrow functions. Would appreciate feedback if anything in this approach seems problematic.
'use strict';
const DIRECTORY = Symbol('the directory of all sheets');
const SHEET = Symbol('an individual sheet');
const COMPOSER = Symbol('the sheet composer');
module.exports = Object.freeze({
getDirectory: () => DIRECTORY,
getSheet: () => SHEET,
getComposer: () => COMPOSER
});
since python-daemon has not yet supported python 3.x, and from what can be read on the mailing list, it may never will, i have written a new implementation of PEP 3143: pep3143daemon
pep3143daemon should support at least python 2.6, 2.7 and 3.x
It also contains a PidFile class.
The library only depends on the standard library and on the six module.
It can be used as a drop in replacement for python-daemon.
Here is the documentation.
You can use the inbuilt function max()
with multiple arguments:
print max(1, 2, 3)
or a list:
list = [1, 2, 3]
print max(list)
or in fact anything iterable.
You can try this:
pushd ../
maven install [...]
popd
After investigating lots of alternatives, I have come across another approach, suitable for the API 2.0 version.
(VB.NET is my favorite, sooo...)
Public Async Function APIPut_Response(ID as Integer, MyWidget as Widget) as Task(Of HttpResponseMessage)
Dim DesiredContent as HttpContent = New StringContent(JsonConvert.SerializeObject(MyWidget))
Return Await APIClient.PutAsync(String.Format("api/widget/{0}", ID), DesiredContent)
End Function
Good luck! For me this worked out (in the end!).
Regards, Peter
I think you'll get what you want with the -maxdepth 1
option, based on your current command structure. If not, you can try looking at the man page for find
.
Relevant entry (for convenience's sake):
-maxdepth levels
Descend at most levels (a non-negative integer) levels of direc-
tories below the command line arguments. `-maxdepth 0' means
only apply the tests and actions to the command line arguments.
Your options basically are:
# Do NOT show hidden files (beginning with ".", i.e., .*):
find DirsRoot/* -maxdepth 0 -type f
Or:
# DO show hidden files:
find DirsRoot/ -maxdepth 1 -type f
give the td padding
If all you are trying to do is get the value out of the hashmap itself, you can do something like the following:
for (Object key : map.keySet()) {
Object value = map.get(key);
//TODO: this
}
Or, you can iterate over the entries of a map, if that is what you are interested in:
for (Map.Entry<Object, Object> entry : map.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
//TODO: other cool stuff
}
As a community, we might be able to give you better/more appropriate answers if we had some idea why you needed the indexes or what you thought the indexes could do for you.
None of the above solutions seems to work in my case, with matplotlib 3.1.0
and Python 3.7.3
. Either both the figures show up on calling show()
or none show up in different answers posted above.
Building upon @Ivan's answer, and taking hint from here, the following seemed to work well for me:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1) # Creates figure fig and add an axes, ax.
fig2, ax2 = plt.subplots(1) # Another figure
ax.plot(range(20)) #Add a straight line to the axes of the first figure.
ax2.plot(range(100)) #Add a straight line to the axes of the first figure.
# plt.close(fig) # For not showing fig
plt.close(fig2) # For not showing fig2
plt.show()
If you are a java guy simple place your angular folder in web content folder of your web application and deploy to your tomcat server. Super easy !
JavaScript
<script language="javascript">
var flag=0;
function username()
{
user=loginform.username.value;
if(user=="")
{
document.getElementById("error0").innerHTML="Enter UserID";
flag=1;
}
}
function password()
{
pass=loginform.password.value;
if(pass=="")
{
document.getElementById("error1").innerHTML="Enter password";
flag=1;
}
}
function check(form)
{
flag=0;
username();
password();
if(flag==1)
return false;
else
return true;
}
</script>
HTML
<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">
<div id="error0"></div>
<input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
controls">
<div id="error1"></div>
<input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">
<button type="submit" class="btn">Sign in</button>
</div>
</div>
</form>
In Windows 10 using node v6.11.2 and npm v3.10.10, in order to execute directly in any folder:
> node-sass [options] <input.scss> [output.css]
I only followed the instructions in node-sass Github:
Add node-gyp prerequisites by running as Admin in a Powershell (it takes a while):
> npm install --global --production windows-build-tools
In a normal command-line shell (Win+R+cmd+Enter) run:
> npm install -g node-gyp
> npm install -g node-sass
The -g
places these packages under %userprofile%\AppData\Roaming\npm\node_modules
. You may check that npm\node_modules\node-sass\bin\node-sass
now exists.
Check if your local account (not the System) PATH
environment variable contains:
%userprofile%\AppData\Roaming\npm
If this path is not present, npm and node may still run, but the modules bin files will not!
Close the previous shell and reopen a new one and run either > node-gyp
or > node-sass
.
Note:
windows-build-tools
may not be necessary (if no compiling is done? I'd like to read if someone made it without installing these tools), but it did add to the admin account the GYP_MSVS_VERSION
environment variable with 2015
as a value.> uglifyjs main.js main.min.js
and > mocha
You need to specify the minimum width of the field.
String.format("%" + numberOfSpaces + "s", "");
Why do you want to generate a String of spaces of a certain length.
If you want a column of this length with values then you can do:
String.format("%" + numberOfSpaces + "s", "Hello");
which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.
just type clrscr(); function in void main().
as example:
void main()
{
clrscr();
printf("Hello m fresher in programming c.");
getch();
}
clrscr();
function easy to clear screen.
The test slice provided in Spring Boot 1.4 brought feature oriented test capabilities.
For example,
@JsonTest provides a simple Jackson environment to test the json serialization and deserialization.
@WebMvcTest provides a mock web environment, it can specify the controller class for test and inject the MockMvc in the test.
@WebMvcTest(PostController.class)
public class PostControllerMvcTest{
@Inject MockMvc mockMvc;
}
@DataJpaTest will prepare an embedded database and provides basic JPA environment for the test.
@RestClientTest provides REST client environment for the test, esp the RestTemplateBuilder etc.
These annotations are not composed with SpringBootTest, they are combined with a series of AutoconfigureXXX
and a @TypeExcludesFilter
annotations.
Have a look at @DataJpaTest
.
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@OverrideAutoConfiguration(enabled = false)
@TypeExcludeFilters(DataJpaTypeExcludeFilter.class)
@Transactional
@AutoConfigureCache
@AutoConfigureDataJpa
@AutoConfigureTestDatabase
@AutoConfigureTestEntityManager
@ImportAutoConfiguration
public @interface DataJpaTest {}
You can add your @AutoconfigureXXX annotation to override the default config.
@AutoConfigureTestDatabase(replace=NONE)
@DataJpaTest
public class TestClass{
}
Let's have a look at your problem,
@DataJpaTest
and @SpringBootTest
, as said above @DataJpaTest
will build the configuration in its own way(eg. by default, it will try to prepare an embedded H2 instead) from the application configuration inheritance. @DataJpaTest
is designated for test slice.@DataJpaTest
, please read this official blog entry from Spring.io for this topic,(a little tedious).Application
into smaller configurations by features, such as WebConfig
, DataJpaConfig
etc. A full featured configuration(mixed web, data, security etc) also caused your test slice based tests to be failed. Check the test samples in my sample.order
from base
arrange
from dplyr
setorder
and setorderv
from data.table
arrange
from plyr
sort
from taRifx
orderBy
from doBy
sortData
from Deducer
Most of the time you should use the dplyr
or data.table
solutions, unless having no-dependencies is important, in which case use base::order
.
I recently added sort.data.frame to a CRAN package, making it class compatible as discussed here: Best way to create generic/method consistency for sort.data.frame?
Therefore, given the data.frame dd, you can sort as follows:
dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"),
levels = c("Low", "Med", "Hi"), ordered = TRUE),
x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
z = c(1, 1, 1, 2))
library(taRifx)
sort(dd, f= ~ -z + b )
If you are one of the original authors of this function, please contact me. Discussion as to public domaininess is here: https://chat.stackoverflow.com/transcript/message/1094290#1094290
You can also use the arrange()
function from plyr
as Hadley pointed out in the above thread:
library(plyr)
arrange(dd,desc(z),b)
Benchmarks: Note that I loaded each package in a new R session since there were a lot of conflicts. In particular loading the doBy package causes sort
to return "The following object(s) are masked from 'x (position 17)': b, x, y, z", and loading the Deducer package overwrites sort.data.frame
from Kevin Wright or the taRifx package.
#Load each time
dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"),
levels = c("Low", "Med", "Hi"), ordered = TRUE),
x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
z = c(1, 1, 1, 2))
library(microbenchmark)
# Reload R between benchmarks
microbenchmark(dd[with(dd, order(-z, b)), ] ,
dd[order(-dd$z, dd$b),],
times=1000
)
Median times:
dd[with(dd, order(-z, b)), ]
778
dd[order(-dd$z, dd$b),]
788
library(taRifx)
microbenchmark(sort(dd, f= ~-z+b ),times=1000)
Median time: 1,567
library(plyr)
microbenchmark(arrange(dd,desc(z),b),times=1000)
Median time: 862
library(doBy)
microbenchmark(orderBy(~-z+b, data=dd),times=1000)
Median time: 1,694
Note that doBy takes a good bit of time to load the package.
library(Deducer)
microbenchmark(sortData(dd,c("z","b"),increasing= c(FALSE,TRUE)),times=1000)
Couldn't make Deducer load. Needs JGR console.
esort <- function(x, sortvar, ...) {
attach(x)
x <- x[with(x,order(sortvar,...)),]
return(x)
detach(x)
}
microbenchmark(esort(dd, -z, b),times=1000)
Doesn't appear to be compatible with microbenchmark due to the attach/detach.
m <- microbenchmark(
arrange(dd,desc(z),b),
sort(dd, f= ~-z+b ),
dd[with(dd, order(-z, b)), ] ,
dd[order(-dd$z, dd$b),],
times=1000
)
uq <- function(x) { fivenum(x)[4]}
lq <- function(x) { fivenum(x)[2]}
y_min <- 0 # min(by(m$time,m$expr,lq))
y_max <- max(by(m$time,m$expr,uq)) * 1.05
p <- ggplot(m,aes(x=expr,y=time)) + coord_cartesian(ylim = c( y_min , y_max ))
p + stat_summary(fun.y=median,fun.ymin = lq, fun.ymax = uq, aes(fill=expr))
(lines extend from lower quartile to upper quartile, dot is the median)
Given these results and weighing simplicity vs. speed, I'd have to give the nod to arrange
in the plyr
package. It has a simple syntax and yet is almost as speedy as the base R commands with their convoluted machinations. Typically brilliant Hadley Wickham work. My only gripe with it is that it breaks the standard R nomenclature where sorting objects get called by sort(object)
, but I understand why Hadley did it that way due to issues discussed in the question linked above.
You can have a different goroutine that detects syscall.SIGINT and syscall.SIGTERM signals and relay them to a channel using signal.Notify. You can send a hook to that goroutine using a channel and save it in a function slice. When the shutdown signal is detected on the channel, you can execute those functions in the slice. This can be used to clean up the resources, wait for running goroutines to finish, persist data, or print partial run totals.
I wrote a small and simple utility to add and run hooks at shutdown. Hope it can be of help.
https://github.com/ankit-arora/go-utils/blob/master/go-shutdown-hook/shutdown-hook.go
You can do this in a 'defer' fashion.
example for shutting down a server gracefully :
srv := &http.Server{}
go_shutdown_hook.ADD(func() {
log.Println("shutting down server")
srv.Shutdown(nil)
log.Println("shutting down server-done")
})
l, err := net.Listen("tcp", ":3090")
log.Println(srv.Serve(l))
go_shutdown_hook.Wait()
You have to create the .ssh folder yourself for saving ssh keys.
By the way, I used this path style: C:/Users/you/.ssh/id_rsa
You can do it via router as well, similar to Francesco answer but with less clutter in router config
Route::get('/artisan/{cmd}', function($cmd) {
$cmd = trim(str_replace("-",":", $cmd));
$validCommands = ['cache:clear', 'optimize', 'route:cache', 'route:clear', 'view:clear', 'config:cache'];
if (in_array($cmd, $validCommands)) {
Artisan::call($cmd);
return "<h1>Ran Artisan command: {$cmd}</h1>";
} else {
return "<h1>Not valid Artisan command</h1>";
}
});
Then run them via visiting http://myapp.test/artisan/cache-clear etc If you need to add/edit valid Artisan commands just update the $validCommands array.
C++ uses structs primarily for 1) backwards compatibility with C and 2) POD types. C structs do not have methods, inheritance or visibility.
I noticed that there is another CSS selector that does the same thing . The syntax is as follows :
[id|="name_id"]
This will select all elements ID which begins with the word enclosed in double quotes.
Try This
var data = 'allow~5';
var result=data.split('~');
RESULT
alert(result[0]);
You may try Easy Python Decompiler. It's based on Decompyle++ and Uncompyle2. It's supports decompiling python versions 1.0-3.3
Note: I am the author of the above tool.
If you are using Angular UI Router, you can listen for the $viewContentLoaded
event.
"$viewContentLoaded - fired once the view is loaded, after the DOM is rendered. The '$scope' of the view emits the event." - Link
$scope.$on('$viewContentLoaded',
function(event){ ... });
I ran into this issue with the Oracle 11R2 client. Not sure if the Oracle installer did this or someone did it here before i arrived. It was not 64-bit vs 32-bit, all was 64-bit.
The error was that libexpat.so.1
was not a symbolic link.
It turned out that there were two identical files, libexpat.so.1.5.2
and libexpat.so.1
. Removing the offending file and making it a symlink to the 1.5.2 version caused the error to go away.
Makes sense that you'd want the well-known name to be a symlink to the current version. If you do this, it's less likely that you'll end up with a stale library.
You need to specify the number of rows which should be deleted. In your case (and I assume that you only want to keep one) this can be done like this:
DELETE FROM your_table WHERE id_users=1 AND id_product=2
LIMIT (SELECT COUNT(*)-1 FROM your_table WHERE id_users=1 AND id_product=2)
This will keep the right aspect ratio.
public ImageIcon scaleImage(ImageIcon icon, int w, int h)
{
int nw = icon.getIconWidth();
int nh = icon.getIconHeight();
if(icon.getIconWidth() > w)
{
nw = w;
nh = (nw * icon.getIconHeight()) / icon.getIconWidth();
}
if(nh > h)
{
nh = h;
nw = (icon.getIconWidth() * nh) / icon.getIconHeight();
}
return new ImageIcon(icon.getImage().getScaledInstance(nw, nh, Image.SCALE_DEFAULT));
}