I've been told that Python 3.3+ adds list.copy()
method, which should be as fast as slicing:
newlist = old_list.copy()
For code mirror divs refer to the manual, these sections might be useful to you:
http://codemirror.net/demo/fullscreen.html
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
theme: "night",
extraKeys: {
"F11": function(cm) {
cm.setOption("fullScreen", !cm.getOption("fullScreen"));
},
"Esc": function(cm) {
if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
}
}
});
And also take a look at:
http://codemirror.net/demo/resize.html
Also a comment:
Inline styling is horrible you should avoid this at all costs, not only will it confuse you, it's poor practice.
To show current language, you can use:
<?php echo $lang=get_bloginfo("language"); ?>
Plain and simple
Found a very easily implemented fix. Set the focus to a text element that has a font size of 50px on completion of the form. It does not seem to work if the text element is hidden but hiding this element is easily done by setting the elements color properties to have no opacity.
If you are running cmake
to generate SomeLib
yourself (say as part of a superbuild), consider using the User Package Registry. This requires no hard-coded paths and is cross-platform. On Windows (including mingw64) it works via the registry. If you examine how the list of installation prefixes is constructed by the CONFIG
mode of the find_packages() command, you'll see that the User Package Registry is one of elements.
Brief how-to
Associate the targets of SomeLib
that you need outside of that external project by adding them to an export set in the CMakeLists.txt
files where they are created:
add_library(thingInSomeLib ...)
install(TARGETS thingInSomeLib Export SomeLib-export DESTINATION lib)
Create a XXXConfig.cmake
file for SomeLib
in its ${CMAKE_CURRENT_BUILD_DIR}
and store this location in the User Package Registry by adding two calls to export() to the CMakeLists.txt
associated with SomeLib
:
export(EXPORT SomeLib-export NAMESPACE SomeLib:: FILE SomeLibConfig.cmake) # Create SomeLibConfig.cmake
export(PACKAGE SomeLib) # Store location of SomeLibConfig.cmake
Issue your find_package(SomeLib REQUIRED)
commmand in the CMakeLists.txt
file of the project that depends on SomeLib
without the "non-cross-platform hard coded paths" tinkering with the CMAKE_MODULE_PATH
.
When it might be the right approach
This approach is probably best suited for situations where you'll never use your software downstream of the build directory (e.g., you're cross-compiling and never install anything on your machine, or you're building the software just to run tests in the build directory), since it creates a link to a .cmake file in your "build" output, which may be temporary.
But if you're never actually installing SomeLib
in your workflow, calling EXPORT(PACKAGE <name>)
allows you to avoid the hard-coded path. And, of course, if you are installing SomeLib
, you probably know your platform, CMAKE_MODULE_PATH
, etc, so @user2288008's excellent answer will have you covered.
Check whether you have given python PATH in environmental variables properly.
If not, then set python path. Then use:
$ python -m notebook
If you'd like to have the date in English:
>>> from datetime import datetime
>>> datetime.today().strftime('%A')
'Wednesday'
Read more: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
you should see this tutorial: https://scotch.io/@micwanyoike/how-to-add-fonts-to-a-react-project
import WebFont from 'webfontloader';
WebFont.load({
google: {
families: ['Titillium Web:300,400,700', 'sans-serif']
}
});
I just tried this method and I can say that it works very well ;)
A mask defines which bits you want to keep, and which bits you want to clear.
Masking is the act of applying a mask to a value. This is accomplished by doing:
Below is an example of extracting a subset of the bits in the value:
Mask: 00001111b
Value: 01010101b
Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:
Mask: 00001111b
Value: 01010101b
Result: 00000101b
Masking is implemented using AND, so in C we get:
uint8_t stuff(...) {
uint8_t mask = 0x0f; // 00001111b
uint8_t value = 0x55; // 01010101b
return mask & value;
}
Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &
, and >>
(shift right). This is how we can extract the four bytes from a 32-bit integer:
void more_stuff(uint32_t value) { // Example value: 0x01020304
uint32_t byte1 = (value >> 24); // 0x01020304 >> 24 is 0x01 so
// no masking is necessary
uint32_t byte2 = (value >> 16) & 0xff; // 0x01020304 >> 16 is 0x0102 so
// we must mask to get 0x02
uint32_t byte3 = (value >> 8) & 0xff; // 0x01020304 >> 8 is 0x010203 so
// we must mask to get 0x03
uint32_t byte4 = value & 0xff; // here we only mask, no shifting
// is necessary
...
}
Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:
uint32_t byte3 = (value & 0xff00) >> 8;
You can use inner divs to set the margin.
<div style="display: table-cell;">
<div style="margin:5px;background-color: red;">1</div>
</div>
<div style="display: table-cell; ">
<div style="margin:5px;background-color: green;">1</div>
</div>
In python functions aren't accessible magically from everywhere (like they are in say, php). They have to be declared first. So this will work:
def pyth_test (x1, x2):
print x1 + x2
pyth_test(1, 2)
But this won't:
pyth_test(1, 2)
def pyth_test (x1, x2):
print x1 + x2
You can throw your own custom errors by extending the Exception class.
class CustomException : Exception {
[string] $additionalData
CustomException($Message, $additionalData) : base($Message) {
$this.additionalData = $additionalData
}
}
try {
throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
# NOTE: To access your custom exception you must use $_.Exception
Write-Output $_.Exception.additionalData
# This will produce the error message: Didn't catch it the second time
throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}
If you really want to run Jenkins as you, I suggest you check out my Jenkins.app. An alternative, easy way to run Jenkins on Mac.
See https://github.com/stisti/jenkins-app/
Download it from https://github.com/stisti/jenkins-app/downloads
I guess you can install it via Parallel or in any other Virtual machine with windows in it
Remember that in order to query the IEnumerable you need to reference system.linq.
It will give you the extension object needed to do:
CaimsList.FirstOrDefault(x=>x.Type =="variableName").toString();
Our server calls stored procs from Java like so - works on both SQL Server 2000 & 2008:
String SPsql = "EXEC <sp_name> ?,?"; // for stored proc taking 2 parameters
Connection con = SmartPoolFactory.getConnection(); // java.sql.Connection
PreparedStatement ps = con.prepareStatement(SPsql);
ps.setEscapeProcessing(true);
ps.setQueryTimeout(<timeout value>);
ps.setString(1, <param1>);
ps.setString(2, <param2>);
ResultSet rs = ps.executeQuery();
For express 4.16+, no need to install body-parser, use the following:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/your/path', (req, res) => {
const body = req.body;
...
}
Try using git log -n 1
after doing a git checkout branchname
. This shows the commit hash, author, date and commit message for the latest commit.
Perform a git pull origin/branchname
first, to make sure your local repo matches upstream.
If perhaps you would only like to see a list of the commits your local branch is behind on the remote branch do this:
git fetch origin
git cherry localbranch remotebranch
This will list all the hashes of the commits that you have not yet merged into your local branch.
I used Christian's Feb 12 solution and I'm also just beginning to learn PowerShell. As far as attachments, I was poking around with Get-Member learning how it works and noticed that Send() has two definitions... the second definition takes a System.Net.Mail.MailMessage object which allows for Attachments and many more powerful and useful features like Cc and Bcc. Here's an example that has attachments (to be mixed with his above example):
# append to Christian's code above --^
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
$emailMessage.To.Add($EmailTo)
$emailMessage.Subject = $Subject
$emailMessage.Body = $Body
$emailMessage.Attachments.Add("C:\Test.txt")
$SMTPClient.Send($emailMessage)
Enjoy!
The get
property works great, and you can also use a binded closure for "expensive" functions that should only run once (this only works with var
, not with const
or let
)
var info = {
address: (function() {
return databaseLookup(this.id)
}).bind(info)(),
get fullName() {
console.log('computing fullName...')
return `${this.first} ${this.last}`
},
id: '555-22-9999',
first: 'First',
last: 'Last',
}
function databaseLookup() {
console.log('fetching address from remote server (runs once)...')
return Promise.resolve(`22 Main St, City, Country`)
}
// test
(async () => {
console.log(info.fullName)
console.log(info.fullName)
console.log(await info.address)
console.log(await info.address)
console.log(await info.address)
console.log(await info.address)
})()
_x000D_
It is only possible to do this cross domain if you have access to implement JS on both domains. If you have that, then here is a little library that solves all the problems with sizing iFrames to their contained content.
https://github.com/davidjbradshaw/iframe-resizer
It deals with the cross domain issue by using the post-message API, and also detects changes to the content of the iFrame in a few different ways.
Works in all modern browsers and IE8 upwards.
declare new variable that the value contain the path of image
const imgLink = require('../../assets/your-image.png')
then call the variable
export default {
name: 'onepage',
data(){
return{
img: imgLink,
}
}
}
bind that on html, this the example:
<a href="#"><img v-bind:src="img" alt="" class="logo"></a>
hope it will help
The problem solved when I don't use any declaration like var, let or const
To add a 1dp
white border at the bottom only and to have a transparent background you can use the following which is simpler than most answers here.
For the TextView
or other view add:
android:background="@drawable/borderbottom"
And in the drawable
directory add the following XML, called borderbottom.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="-2dp" android:left="-2dp" android:right="-2dp">
<shape android:shape="rectangle">
<stroke android:width="1dp" android:color="#ffffffff" />
<solid android:color="#00000000" />
</shape>
</item>
</layer-list>
If you want a border at the top, change the android:top="-2dp"
to android:bottom="-2dp"
The colour does not need to be white and the background does not need to be transparent either.
The solid
element may not be required. This will depend on your design (thanks V. Kalyuzhnyu).
Basically, this XML will create a border using the rectangle shape, but then pushes the top, right and left sides beyond the render area for the shape. This leaves just the bottom border visible.
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).
upstream
defines a cluster that you can proxy requests to. It's commonly used for defining either a web server cluster for load balancing, or an app server cluster for routing / load balancing.
If it doesn't work with npm uninstall <module_name>
try it globally by typing -g
.
Maybe you just need to do it as an superUser/administrator with sudo npm uninstall <module_name>
.
try this..
<tr ng-repeat='item in items'>
<td>{{item.Name}}</td>
<td>{{item.Price}}</td>
<td>{{item.Quantity}}</td>
</tr>
Traversal over the large map entrySet()
is much better than the keySet()
. Check this tutorial how they optimise the traversal over the large object with the help of entrySet(
) and how it helps for performance tuning.
For one, you don't seem to be including jQuery itself in the header but only a bunch of plugins. As for the '<' error, it's impossible to tell without seeing the generated HTML.
This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes.
You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from previous state. Incorrect usage of setState() can lead to an infinite loop. Take a look at the example below that shows a typical usage example of this lifecycle method.
componentDidUpdate(prevProps) {
//Typical usage, don't forget to compare the props
if (this.props.userName !== prevProps.userName) {
this.fetchData(this.props.userName);
}
}
Notice in the above example that we are comparing the current props to the previous props. This is to check if there has been a change in props from what it currently is. In this case, there won’t be a need to make the API call if the props did not change.
For more info, refer to the official docs:
This is something that I have used successfully to convert Context
to Activity
when operating within the UI in fragments or custom views. It will unpack ContextWrapper recursively or return null if it fails.
public Activity getActivity(Context context)
{
if (context == null)
{
return null;
}
else if (context instanceof ContextWrapper)
{
if (context instanceof Activity)
{
return (Activity) context;
}
else
{
return getActivity(((ContextWrapper) context).getBaseContext());
}
}
return null;
}
You may try android:focusableInTouchMode="false".
fs.readFile takes a call back which calls response.send as you have shown - good. If you simply replace that with fs.readFileSync, you need to be aware it does not take a callback so your callback which calls response.send will never get called and therefore the response will never end and it will timeout.
You need to show your readFileSync code if you're not simply replacing readFile with readFileSync.
Also, just so you're aware, you should never call readFileSync in a node express/webserver since it will tie up the single thread loop while I/O is performed. You want the node loop to process other requests until the I/O completes and your callback handling code can run.
You should also be aware that if your sites contains link to other external sites you dont control using GET will put that data in the refeerer header on the external sites when they press the links on your site. So transfering login data through GET methods is ALWAYS a big issue. Since that might expose login credentials for easy access by just checking the logs or looking in Google analytics (or similar).
I am using 'ImportJS' plugin by Devin Abbott for auto import and you can install this using below code
npm install --global import-js
For all that struggle with theoretical file paths and examples like I did, here a real world example: Microsoft offers their docs and examples on git hub, unfortunately they do gather all their example files for a large amount of topics in this repository:
https://github.com/microsoftarchive/msdn-code-gallery-community-s-z
I only was interested in the Microsoft Dynamics js files in the path
msdn-code-gallery-community-s-z/Sdk.Soap.js/
so I did the following
create a
msdn-code-gallery-community-s-zSdkSoapjs\.git\info\sparse-checkout
file in my repositories folder on the disk
git sparse-checkout init
in that directory using cmd on windows
The file contents of
msdn-code-gallery-community-s-zSdkSoapjs\.git\info\sparse-checkout
is
Sdk.Soap.js/*
finally do a
git pull origin master
Use SelectTab
like this:
TabPage t = tabControl1.TabPages[2];
tabControl1.SelectTab(t); //go to tab
Use SelectedTab
like this:
TabPage t = tabControl1.TabPages[2];
tabControl1.SelectedTab = t; //go to tab
A "rollback" only works if you used transactions. That way you can group queries together and undo all queries if only one of them fails.
But if you already committed the transaction (or used a regular DELETE-query), the only way of getting your data back is to recover it from a previously made backup.
This will do:
▢
It is ?
(known as a "WHITE SQUARE WITH ROUNDED CORNERS" on fileformat.info)
Or
◻
as ?
(known as a "WHITE MEDIUM SQUARE" on the same website)
Two with shadow:
❏
❑
as ? and ? . The difference between them is the shadows' shape. You can see it if you zoom in or if you print it out. (They are known as "LOWER RIGHT DROP-SHADOWED WHITE SQUARE" and "LOWER RIGHT SHADOWED WHITE SQUARE", respectively).
You can also use
☐
which is ?
(known as a "BALLOT BOX").
A sample is at http://jsfiddle.net/S2QCt/267/
(a note: on the Mac, ▢
is quite nice, because it is bigger and somewhat more elegant than ☐
On Windows, ☐
looks more standard, while ▢
is somewhat small.)
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
void displayBinary(int n)
{
char bistr[1000];
itoa(n,bistr,2); //2 means binary u can convert n upto base 36
printf("%s",bistr);
}
int main()
{
int n;
cin>>n;
displayBinary(n);
getch();
return 0;
}
If you're changing the layout of an existing ImageView, you should be able to simply get the current LayoutParams, change the width/height, and set it back:
android.view.ViewGroup.LayoutParams layoutParams = myImageView.getLayoutParams();
layoutParams.width = 30;
layoutParams.height = 30;
myImageView.setLayoutParams(layoutParams);
I don't know if that's your goal, but if it is, this is probably the easiest solution.
If the yml
is called docker-compose.yml
it can be launched with a simple $ docker-compose up
. The corresponding attachment of a terminal can be simply (consider that the yml
has specified a service called myservice
):
$ docker-compose exec myservice sh
However, if you are using a different yml
file name, such as docker-compose-mycompose.yml
, it should be launched using $ docker-compose -f docker-compose-mycompose.yml up
. To attach an interactive terminal you have to specify the yml
file too, just like:
$ docker-compose -f docker-compose-mycompose.yml exec myservice sh
**just copy paste this code and run you can see the textbox disabled **
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style>.container{float:left;width:200px;height:25px;position:relative;}
.container input{float:left;width:200px;height:25px;}
.overlay{display:block;width:208px;position:absolute;top:0px;left:0px;height:32px;}
</style>
</head>
<body>
<div class="container">
<input type="text" value="[email protected]" />
<div class="overlay">
</div>
</div>
</body>
</html>
example :
df1.iloc[:5]
df1.loc['A','B']
It took me like an hour to figure it out, but trailing commas (which work in JavaScript) fail in PHP.
This is what fixed it for me:
str_replace([PHP_EOL, ",}"], ["", "}"], $JSON);
std::string::data
would seem to be sufficient and most efficient. If you want to have non-const memory to manipulate (strange for encryption) you can copy the data to a buffer using memcpy:
unsigned char buffer[mystring.length()];
memcpy(buffer, mystring.data(), mystring.length());
STL fanboys would encourage you to use std::copy instead:
std::copy(mystring.begin(), mystring.end(), buffer);
but there really isn't much of an upside to this. If you need null termination use std::string::c_str()
and the various string duplication techniques others have provided, but I'd generally avoid that and just query for the length
. Particularly with cryptography you just know somebody is going to try to break it by shoving nulls in to it, and using std::string::data()
discourages you from lazily making assumptions about the underlying bits in the string.
You could use a separate file, like npm_globals.txt
, instead of package.json
. This file would contain each module on a new line like this,
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
Then in the command line run,
< npm_globals.txt xargs npm install -g
Check that they installed properly with,
npm list -g --depth=0
As for whether you should do this or not, I think it all depends on use case. For most projects, this isn't necessary; and having your project's package.json
encapsulate these tools and dependencies together is much preferred.
But nowadays I find that I'm always installing create-react-app
and other CLI's globally when I jump on a new machine. It's nice to have an easy way to install a global tool and its dependencies when versioning doesn't matter much.
And nowadays, I'm using npx
, an npm package runner, instead of installing packages globally.
It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.
The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:
You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:
Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:
#toolbar=0&navpanes=0
So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.
string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);
You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.
I asume you have connected to your database already.
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
$col = 0;
foreach($row_data as $key=>$value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
Well, it's part of BitBucket philosophy and workflow:
i.e you can't (in usual case) commit into foreign repo under own credentials.
You have two possible solutions:
You can get the output of that command and put it in a variable. then use heredoc
. for example:
nc -l -p 80 <<< "tested like a charm";
can be written like:
nc -l -p 80 <<EOF
tested like a charm
EOF
and like this (this is what you want):
text="tested like a charm"
nc -l -p 80 <<EOF
$text
EOF
Practical example in busybox
under docker
container:
kasra@ubuntu:~$ docker run --rm -it busybox
/ # nc -l -p 80 <<< "tested like a charm";
sh: syntax error: unexpected redirection
/ # nc -l -p 80 <<EOL
> tested like a charm
> EOL
^Cpunt! => socket listening, no errors. ^Cpunt! is result of CTRL+C signal.
/ # text="tested like a charm"
/ # nc -l -p 80 <<EOF
> $text
> EOF
^Cpunt!
what works for me:
1- in styles.xml:
<style name="generalnotitle" parent="Theme.AppCompat.Light" >
<item name="android:windowNoTitle">true</item> <!-- //this -->
</style>
2- in MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide(); //<< this
setContentView(R.layout.activity_main);
}
in manifest inherit the style:
<activity android:name=".MainActivity" android:theme="@style/generalnotitle">
In Oracle, you can simply subtract two dates and get the difference in days. Also note that unlike SQL Server or MySQL, in Oracle you cannot perform a select
statement without a from
clause. One way around this is to use the builtin dummy table, dual
:
SELECT TO_DATE('2000-01-02', 'YYYY-MM-DD') -
TO_DATE('2000-01-01', 'YYYY-MM-DD') AS DateDiff
FROM dual
I came across this post searching how to add an extra directory for resources. I found a solution that may be useful to someone. Here is my final configuration to get that:
sourceSets {
main {
resources {
srcDirs "src/main/resources", "src/main/configs"
}
}
}
function UpdateClick(btn) {
for (i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i]);
if (Page_Validators[i].isvalid == false)
return false;
}
btn.disabled = 'false';
btn.value = 'Please Wait...';
return true;
}
This worked for me!!
SELECT * FROM `users` where `created_at` BETWEEN CURDATE()-7 AND CURDATE()
You can refer to this link.
Install ODAC 64 bit driver using CMD after install ODAC 32 bit:
Type install.bat all c:/oracle odac
command and press Enter.
Installation file will be located at “c:/oracle” folder.
When installing Oracle 11g client 32 and 64 bit, you must change oracle base path: “c:/oracle”
You can try the Boost Tokenizer library, in particular the Escaped List Separator
In addition to VAV's answer, The first one was most useful in my environment
select * from USER_ROLE_PRIVS where USERNAME='SAMPLE';
select * from USER_TAB_PRIVS where Grantee = 'SAMPLE';
select * from USER_SYS_PRIVS where USERNAME = 'SAMPLE';
In my case:-
Answer:-
I just deleted the react-native-firebase
folder which will be inside the node_modules
folder, that's it then I could run the app successfully.
And one more thing don't forget to remove react-native-firebase
but not @react-native-firebase
in package.json file. So that next time when you run npm I
or yarn
. This won't get installed in your app.
This package was causing the issue.
For those that are not overflowing but hiding by negative margin:
$('#element').height() + -parseInt($('#element').css("margin-top"));
(ugly but only one that works so far)
If you don't specify indexes on your initial array, you get the regular numric ones. Arrays must have some form of unique index
The solution you are looking for is in Angular's official tutorial. In this tutorial Phones are loaded from a JSON file using Angulars $http service . In the code below we use $http.get to load a phones.json file saved in the phones directory:
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
});
We then iterate over the phones:
<table>
<tbody ng-repeat="i in phones">
<tr><td>{{i.name}}</td><td>{{$index}}</td></tr>
<tr ng-repeat="e in i.details">
<td>{{$index}}</td>
<td>{{e.foo}}</td>
<td>{{e.bar}}</td></tr>
</tbody>
</table>
Swift:
let fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context)
fetchRequest.includesPropertyValues = false
var error:NSError?
if let results = context.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject] {
for result in results {
context.deleteObject(result)
}
var error:NSError?
if context.save(&error) {
// do something after save
} else if let error = error {
println(error.userInfo)
}
} else if let error = error {
println("error: \(error)")
}
Simply use the question mark trick for null checks:
string displayName = Dictionary.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID))?.Value.DisplayName ?? "DEFINE A DEFAULT DISPLAY NAME HERE";
Postgres 9.5 (released since 2016-01-07) offers an "upsert" command, also known as an ON CONFLICT clause to INSERT:
INSERT ... ON CONFLICT DO NOTHING/UPDATE
It solves many of the subtle problems you can run into when using concurrent operation, which some other answers propose.
You won't be able to convert it directly to long because of the decimal point i think you should convert it into decimal and then convert it into long something like this:
String strValue[i] = "1100.25";
long l1 = Convert.ToInt64(Convert.ToDecimal(strValue));
hope this helps!
CSS3 + jQuery Solution
I wanted a solution that did NOT employ jQuery's fade effect as this causes lag in many mobile devices.
Borrowing from Steve Fenton's answer I have adapted a version of this that fades the image in with the CSS3 transition property and opacity. This also takes into account the problem of browser caching, in which case the image will not show up using CSS.
Here is my code and working fiddle:
HTML
<img src="http://placehold.it/350x150" class="fade-in-on-load">
CSS
.fade-in-on-load {
opacity: 0;
will-change: transition;
transition: opacity .09s ease-out;
}
jQuery Snippet
$(".fade-in-on-load").each(function(){
if (!this.complete) {
$(this).bind("load", function () {
$(this).css('opacity', '1');
});
} else {
$(this).css('opacity', '1');
}
});
What's happening here is the image (or any element) that you want to fade in when it loads will need to have the .fade-in-on-load
class applied to it beforehand. This will assign it a 0 opacity and assign the transition effect, you can edit the fade speed to taste in the CSS.
Then the JS will search each item that has the class and bind the load event to it. Once done, the opacity will be set to 1, and the image will fade in. If the image was already stored in the browser cache already, it will fade in immediately.
Using this for a product listing page.
This may not be the prettiest implementation but it does work well.
You need to set the thumbnail class to position relative then the post-content to absolute.
Check this fiddle
.post-content {
top:0;
left:0;
position: absolute;
}
.thumbnail{
position:relative;
}
Giving it top and left 0 will make it appear in the top left corner.
Since you're writing a calculator that would presumably also accept floats (1.5, 0.03
), a more robust way would be to use this simple helper function:
def convertStr(s):
"""Convert string to either int or float."""
try:
ret = int(s)
except ValueError:
#Try float.
ret = float(s)
return ret
That way if the int conversion doesn't work, you'll get a float returned.
Edit: Your division
function might also result in some sad faces if you aren't fully aware of how python 2.x handles integer division.
In short, if you want 10/2
to equal 2.5
and not 2
, you'll need to do from __future__ import division
or cast one or both of the arguments to float, like so:
def division(a, b):
return float(a) / float(b)
If you need a laymans explanation of the use beyond that provided in the Spring Docs
Consider this code...
class Service {
@Transactional(propagation=Propagation.REQUIRED)
public void doSomething() {
// access a database using a DAO
}
}
When doSomething() is called it knows it has to start a Transaction on the database before executing. If the caller of this method has already started a Transaction then this method will use that same physical Transaction on the current database connection.
This @Transactional
annotation provides a means of telling your code when it executes that it must have a Transaction. It will not run without one, so you can make this assumption in your code that you wont be left with incomplete data in your database, or have to clean something up if an exception occurs.
Transaction management is a fairly complicated subject so hopefully this simplified answer is helpful
I didn't apply paging on my gridview and it extends to more than 600 records (with checkbox, buttons, etc.) and the value of 2001 didn't work. You may increase the value, say 10000 and test.
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="10000" />
</appSettings>
The first case is telling the web server that you are posting JSON data as in:
{ Name : 'John Smith', Age: 23}
The second option is telling the web server that you will be encoding the parameters in the URL as in:
Name=John+Smith&Age=23
You can also embed it in the php. E.g.
<?php
echo "<p style='color:blue; border:2px red solid;'>CSS Styling in php</p>";
?>
hope this help for anyone in the future.
ConfirmDialog('Are you sure');_x000D_
_x000D_
function ConfirmDialog(message) {_x000D_
$('<div></div>').appendTo('body')_x000D_
.html('<div><h6>' + message + '?</h6></div>')_x000D_
.dialog({_x000D_
modal: true,_x000D_
title: 'Delete message',_x000D_
zIndex: 10000,_x000D_
autoOpen: true,_x000D_
width: 'auto',_x000D_
resizable: false,_x000D_
buttons: {_x000D_
Yes: function() {_x000D_
// $(obj).removeAttr('onclick'); _x000D_
// $(obj).parents('.Parent').remove();_x000D_
_x000D_
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');_x000D_
_x000D_
$(this).dialog("close");_x000D_
},_x000D_
No: function() {_x000D_
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');_x000D_
_x000D_
$(this).dialog("close");_x000D_
}_x000D_
},_x000D_
close: function(event, ui) {_x000D_
$(this).remove();_x000D_
}_x000D_
});_x000D_
};
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
_x000D_
I have one other way to do this same thing works perfectly. so the idea behind to show all markers on the screen we need a center lat long and zoom level. here is the function which will give you both and need all marker's Latlng objects as input.
public Pair<LatLng, Integer> getCenterWithZoomLevel(LatLng... l) {
float max = 0;
if (l == null || l.length == 0) {
return null;
}
LatLngBounds.Builder b = new LatLngBounds.Builder();
for (int count = 0; count < l.length; count++) {
if (l[count] == null) {
continue;
}
b.include(l[count]);
}
LatLng center = b.build().getCenter();
float distance = 0;
for (int count = 0; count < l.length; count++) {
if (l[count] == null) {
continue;
}
distance = distance(center, l[count]);
if (distance > max) {
max = distance;
}
}
double scale = max / 1000;
int zoom = ((int) (16 - Math.log(scale) / Math.log(2)));
return new Pair<LatLng, Integer>(center, zoom);
}
This function return Pair object which you can use like
Pair pair = getCenterWithZoomLevel(l1,l2,l3..); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pair.first, pair.second));
you can instead of using padding to keep away your markers from screen boundaries, you can adjust zoom by -1.
You can just:
if(variable||variable===0){
//Yes it is set
//do something
}
else {
//No it is not set
//Or its null
//do something else
}
you can try this (I don't have sql server here today so I can't verify syntax, sorry)
select attributeName
from tableName
where CONVERT(varchar,attributeName,101) BETWEEN '03/01/2009' AND '03/31/2009'
and CONVERT(varchar, attributeName,108) BETWEEN '06:00:00' AND '22:00:00'
and DATEPART(day,attributeName) BETWEEN 2 AND 4
Avoid any?
for large arrays.
any?
is O(n)
empty?
is O(1)
any?
does not check the length but actually scans the whole array for truthy elements.
static VALUE
rb_ary_any_p(VALUE ary)
{
long i, len = RARRAY_LEN(ary);
const VALUE *ptr = RARRAY_CONST_PTR(ary);
if (!len) return Qfalse;
if (!rb_block_given_p()) {
for (i = 0; i < len; ++i) if (RTEST(ptr[i])) return Qtrue;
}
else {
for (i = 0; i < RARRAY_LEN(ary); ++i) {
if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) return Qtrue;
}
}
return Qfalse;
}
empty?
on the other hand checks the length of the array only.
static VALUE
rb_ary_empty_p(VALUE ary)
{
if (RARRAY_LEN(ary) == 0)
return Qtrue;
return Qfalse;
}
The difference is relevant if you have "sparse" arrays that start with lots of nil
values, like for example an array that was just created.
It took me a while to figure this out too. url_for
in Flask looks for endpoints that you specified in the routes.py
script.
So if you have a decorator in your routes.py
file like @blah.route('/folder.subfolder')
then Flask will recognize the command {{ url_for('folder.subfolder') , filename = "some_image.jpg" }}
. The 'folder.subfolder'
argument sends it to a Flask endpoint it recognizes.
However let us say that you stored your image file, some_image.jpg
, in your subfolder, BUT did not specify this subfolder as a route endpoint in your flask routes.py
, your route decorator looks like @blah.routes('/folder')
. You then have to ask for your image file this way:
{{ url_for('folder'), filename = 'subfolder/some_image.jpg' }}
I.E. you tell Flask to go to the endpoint it knows, "folder", then direct it from there by putting the subdirectory path in the filename argument.
try this
$sql= " INSERT INTO users (username, password) VALUES('test', 'test') ";
mysql_query($sql);
$user_id= mysql_insert_id();
if(!empty($user_id) {
$sql=INSERT INTO profiles (userid, bio, homepage) VALUES($user_id,'Hello world!', 'http://www.stackoverflow.com');
/* or
$sql=INSERT INTO profiles (userid, bio, homepage) VALUES(LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com'); */
mysql_query($sql);
};
TLDR; technically space sorts before exclamation mar, and can be used by preceding it with ' or - (which will be ignored in sorting), but exclamation mark follows right after space, and is easier to use.
On windows 7 at least, a minus sign (-) and (') seem to be ignored in a name except for one quirk: in a name that is otherwise identical, the ' will be sorted before -, for example: (a'a) will sort above (a-a)
Empty string will sort above everything else, which means for example aa will sort above aaa because the 'empty string' after two a letters will sort before the third 'a'.
This also means that aa will be sorted above a'a because the 'empty string' between two a letters will sort above the ' mark.
What follows then is, ' alone will sort first, because technically it's an empty string. However adding for example letters behind it will sort the name as if the ' didn't exist.
Since the first 'unignored' character (as far as I know) is space, in case you want to sort 'real names' above others, the best way to go would be ' followed by space, and then the name you want to actually use. For example: (' first)
You can of course top that by using more than one space in the strong, such as (' firster) and (' firstest) with two and three blanks before the f.
While minus sign sorts below ' in otherwise similar name, there's no other difference in sorting (that I know of), and I find minus sign visually clearer, so if I want to put something on top of list, I'd use minus followed by space, then the 'actual name', for example: (- first file -)
If you are worried about using space on the filename, then exclamation mark (!) is the next best thing - and since it can appear as first character on a string, it's easier to use.
Just telling my resolution: in my case, the libraries and projects weren't being added automatically to the classpath (i don't know why), even clicking at the "add to build path" option. So I went on run -> run configurations -> classpath and added everything I needed through there.
ubuntu users:
sudo apt-get install libc6-dev
specially ruby developers that have problem installing gem install json -v '1.8.2'
on their VMs
use from configurations must be very very easy like this :
var config = new MiniConfig("setting.conf");
config.AddOrUpdate("port", "1580");
if (config.TryGet("port", out int port)) // if config exist
{
Console.Write(port);
}
for more details see MiniConfig
Just in case if someone stumbles onto this thread then here is a bullet proof solution to SQL Server stuck in SINGLE USER MODE
-- Get the process ID (spid) of the connection you need to kill
-- Replace 'DBName' with the actual name of the DB
SELECT sd.[name], sp.spid, sp.login_time, sp.loginame
FROM sysprocesses sp
INNER JOIN sysdatabases sd on sp.dbid = sd.dbid
WHERE sd.[name] = 'DBName'
As an alternative, you can also use the command “sp_who” to get the “spid” of the open connection:
-- Or use this SP instead
exec sp_who
-- Then Execute the following and replace the [spid] and [DBName] with correct values
KILL SpidToKillGoesHere
GO
SET DEADLOCK_PRIORITY HIGH
GO
ALTER DATABASE [DBName] SET MULTI_USER WITH ROLLBACK IMMEDIATE
GO
These are timeout values enforced by JVM for TCP connection establishment and waiting on reading data from socket.
If the value is set to infinity, you will not wait forever. It simply means JVM doesn't have timeout and OS will be responsible for all the timeouts. However, the timeouts on OS may be really long. On some slow network, I've seen timeouts as long as 6 minutes.
Even if you set the timeout value for socket, it may not work if the timeout happens in the native code. We can reproduce the problem on Linux by connecting to a host blocked by firewall or unplugging the cable on switch.
The only safe approach to handle TCP timeout is to run the connection code in a different thread and interrupt the thread when it takes too long.
Add the sheet name infront of the cell, e.g.:
=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")
Assumes the sheet name is "stock"
SELECT DISTINCT
and SELECT UNIQUE
behave the same way. While DISTINCT is ANSI SQL standard, UNIQUE is an Oracle specific statement.
SELECT UNIQUE
is invalid syntax. UNIQUE
is keyword for adding unique constraint on the column.
Let me report a very simple solution I found, that is not written in previous answers. I also wanted to set background in an SVG, but I also want that this works in a standalone SVG file.
Well, this solution is really simple, in fact SVG supports style tags, so you can do something like
<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
<style>svg { background-color: red; }</style>
<text>hello</text>
</svg>
%TEMP%
vc_redist.x64
see Download Visual C++ Redistributable for Visual Studio 2015Before answering when to use which one, a little background:
edit: I should mention that this comparison is really from the perspective of using them in a browser with JavaScript. It's not the way either data format has to be used, and there are plenty of good parsers which will change the details to make what I'm saying not quite valid.
JSON is both more compact and (in my view) more readable - in transmission it can be "faster" simply because less data is transferred.
In parsing, it depends on your parser. A parser turning the code (be it JSON or XML) into a data structure (like a map) may benefit from the strict nature of XML (XML Schemas disambiguate the data structure nicely) - however in JSON the type of an item (String/Number/Nested JSON Object) can be inferred syntactically, e.g:
myJSON = {"age" : 12,
"name" : "Danielle"}
The parser doesn't need to be intelligent enough to realise that 12
represents a number, (and Danielle
is a string like any other). So in javascript we can do:
anObject = JSON.parse(myJSON);
anObject.age === 12 // True
anObject.name == "Danielle" // True
anObject.age === "12" // False
In XML we'd have to do something like the following:
<person>
<age>12</age>
<name>Danielle</name>
</person>
(as an aside, this illustrates the point that XML is rather more verbose; a concern for data transmission). To use this data, we'd run it through a parser, then we'd have to call something like:
myObject = parseThatXMLPlease();
thePeople = myObject.getChildren("person");
thePerson = thePeople[0];
thePerson.getChildren("name")[0].value() == "Danielle" // True
thePerson.getChildren("age")[0].value() == "12" // True
Actually, a good parser might well type the age
for you (on the other hand, you might well not want it to). What's going on when we access this data is - instead of doing an attribute lookup like in the JSON example above - we're doing a map lookup on the key name
. It might be more intuitive to form the XML like this:
<person name="Danielle" age="12" />
But we'd still have to do map lookups to access our data:
myObject = parseThatXMLPlease();
age = myObject.getChildren("person")[0].getAttr("age");
EDIT: Original:
In most programming languages (not all, by any stretch) a map lookup such as this will be more costly than an attribute lookup (like we got above when we parsed the JSON).
This is misleading: remember that in JavaScript (and other dynamic languages) there's no difference between a map lookup and a field lookup. In fact, a field lookup is just a map lookup.
If you want a really worthwhile comparison, the best is to benchmark it - do the benchmarks in the context where you plan to use the data.
As I have been typing, Felix Kling has already put up a fairly succinct answer comparing them in terms of when to use each one, so I won't go on any further.
Just a note that as of Ruby 2.0 there is no need to add # encoding: utf-8
. UTF-8 is automatically detected.
Replace
volume = (4 / 3) Math.PI * Math.pow(radius, 3);
With:
volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;
Use spread Operator to get your desired result
var arrayFromSet = [...set];
In most cases getting rid of infinite and null values solve this problem.
get rid of infinite values.
df.replace([np.inf, -np.inf], np.nan, inplace=True)
get rid of null values the way you like, specific value such as 999, mean, or create your own function to impute missing values
df.fillna(999, inplace=True)
You can use new Date().getTimezoneOffset()/60
for the timezone. There is also a toLocaleString()
method for displaying a date using the user's locale.
Here's the whole list: Working with Dates
In SQL Server I would use:
WHERE CHARINDEX(CHAR(13), name) <> 0 OR CHARINDEX(CHAR(10), name) <> 0
This will search for both carriage returns and line feeds.
If you want to search for tabs too just add:
OR CHARINDEX(CHAR(9), name) <> 0
if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):
count before dedupe:
df.count()
do the de-dupe (convert the column you are de-duping to string type):
from pyspark.sql.functions import col
df = df.withColumn('colName',col('colName').cast('string'))
df.drop_duplicates(subset=['colName']).count()
can use a sorted groupby to check to see that duplicates have been removed:
df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)
Try this one to disable width-scrolling just for body
the all document just is body
body{overflow-x: hidden;}
Here is yet another solution (one-liner), involving using the itertools.combinations
function, but here we use a double list comprehension (as opposed to a for loop or sum):
def combs(x):
return [c for i in range(len(x)+1) for c in combinations(x,i)]
Demo:
>>> combs([1,2,3,4])
[(),
(1,), (2,), (3,), (4,),
(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4),
(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4),
(1, 2, 3, 4)]
I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.
I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"s","l","m"}, {-1,1,0})
and it started working when I did this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"l","m","s"}, {1,0,-1})
I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.
Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.
@staticmethod
function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.
@classmethod
function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance, can be overridden by subclass. That’s because the first argument for @classmethod
function must always be cls (class)
.
here is good link to this topic.
This error usually occurs when the IDE has a problem due to a crash or other failure and it still has a hold on the EXE, preventing the user (yourself) from overwriting / deleting the EXE during a rebuild.
What programming languages can one use to develop iPhone, iPod Touch and iPad (iOs) applications?
Ruby, Python, Lua, Scheme, Lisp, Smalltalk, C#, Haskell, ActionScript, JavaScript, Objective-C, C++, C. That's just the ones that pop into my head right now. I'm sure there's hundreds if not thousands of others. (E.g. there's no reason why you couldn't use any .NET language with MonoTouch, i.e. VB.NET, F#, Nemerle, Boo, Cobra, ...)
Also are there plans in the future to expand the amount of programming languages that iOs will support?
Sure. Pretty much every programming language community on this planet is currently working on getting their language to run on iOS.
Also, a lot of people are working on programming languages specifically designed for touch devices such as iPod touch, iPhone and iPad, e.g. Phil Mercurio's Thyrd language.
if you POJO contains any other model inside that should also implements Serializable
Both source and target should be specified. I recommend providing ant defaults, that way you do not need to specify source/target attribute for every javac task:
<property name="ant.build.javac.source" value="1.5"/>
<property name="ant.build.javac.target" value="1.5"/>
See Java cross-compiling notes for more information.
There is a special function made for this Path.Combine()
var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullpath = path.Combine(folder,"Tasks");
The pyplot functions you are calling, axhline()
and axvline()
draw lines that span a portion of the axis range, regardless of coordinates. The parameters xmin
or ymin
use value 0.0 as the minimum of the axis and 1.0 as the maximum of the axis.
Instead, use plt.plot((x1, x2), (y1, y2), 'k-')
to draw a line from the point (x1, y1) to the point (x2, y2) in color k. See pyplot.plot
.
Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.
Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.
var data = [ // The data
['ten', [
'eleven','twelve'
]],
['twenty', [
'twentyone', 'twentytwo'
]]
];
$a = $('#a'); // The dropdowns
$b = $('#b');
for(var i = 0; i < data.length; i++) {
var first = data[i][0];
$a.append($("<option>"). // Add options
attr("value",first).
data("sel", i).
text(first));
}
$a.change(function() {
var index = $(this).children('option:selected').data('sel');
var second = data[index][1]; // The second-choice data
$b.html(''); // Clear existing options in second dropdown
for(var j = 0; j < second.length; j++) {
$b.append($("<option>"). // Add options
attr("value",second[j]).
data("sel", j).
text(second[j]));
}
}).change(); // Trigger once to add options at load of first choice
swift 3
if View controller-based status bar appearance = YES in Info.plist
then use this extension for all NavigationController
extension UINavigationController
{
override open var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
if there is no UINavigationController and only have UIViewController then use Below code:
extension UIViewController
{
override open var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
Batch file for setting a new dns server
@echo off
rem usage: setdns <dnsserver> <interface>
rem default dsnserver is dhcp
rem default interface is Wi-Fi
set dnsserver="%1"
if %dnsserver%=="" set dnsserver="dhcp"
set interface="%2"
if %interface%=="" set interface="Wi-Fi"
echo Showing current DNS setting for interface a%interface%
netsh interface ipv4 show dnsserver %interface%
echo Changing dnsserver on interface %interface% to %dnsserver%
if %dnsserver% == "dhcp" netsh interface ipv4 set dnsserver %interface% %dnsserver%
if NOT %dnsserver% == "dhcp" netsh interface ipv4 add dnsserver %interface% address=%dnsserver% index=1
echo Showing new DNS setting for interface %interface%
netsh interface ipv4 show dnsserver %interface%
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
First represent the epoch of the millisecond time as a date (usually 1/1/1970), then add your millisecond time divided by the number of milliseconds in a day (86400000):
=DATE(1970,1,1)+(A1/86400000)
If your cell is properly formatted, you should see a human-readable date/time.
I like both @Qiao first answer and @Or's addition. For a sake of a little less processing I would like to add to Or's answer.
In @Or's answer keeping track of visited node is great. We can also allow the program to exit sooner that it currently is. At some point in the for loop the current_neighbour
will have to be the end
, and once that happens the shortest path is found and program can return.
I would modify the the method as follow, pay close attention to the for loop
graph = {
1: [2, 3, 4],
2: [5, 6],
3: [10],
4: [7, 8],
5: [9, 10],
7: [11, 12],
11: [13]
}
def bfs(graph_to_search, start, end):
queue = [[start]]
visited = set()
while queue:
# Gets the first path in the queue
path = queue.pop(0)
# Gets the last node in the path
vertex = path[-1]
# Checks if we got to the end
if vertex == end:
return path
# We check if the current node is already in the visited nodes set in order not to recheck it
elif vertex not in visited:
# enumerate all adjacent nodes, construct a new path and push it into the queue
for current_neighbour in graph_to_search.get(vertex, []):
new_path = list(path)
new_path.append(current_neighbour)
queue.append(new_path)
#No need to visit other neighbour. Return at once
if current_neighbour == end
return new_path;
# Mark the vertex as visited
visited.add(vertex)
print bfs(graph, 1, 13)
The output and everything else will be the same. However, the code will take less time to process. This is especially useful on larger graphs. I hope this helps someone in the future.
I had the same problem as you, Noboby can understand me, But I solved it in this way.
SELECT NAME, TELEFONE, DATA
FROM [sheet1$a1:q633]
WHERE NAME IN (SELECT * FROM [sheet2$a1:a2])
you need insert a parameter in other sheet, the SQL will consider that information like as database, then you can select the information and compare them into parameter you like.
For recent versions of Gradle (I tested with the 6.4.1 version):
gradle dependencies --configuration compileClasspath
or if you're using the Gradle Wrapper:
gradlew dependencies --configuration compileClasspath
When building for Android with the 'debug' and 'release' compilation profiles, the debugCompileClasspath
and releaseCompileClasspath
configurations can be used instead of compileClasspath
.
It is also available in general settings
Settings -> Security -> Verify Apps
Just un-check it.
( I am running 4.2.2 but most probably it should be available in 4.0 and higher. Cant say about previous versions ... )
There are several ways to do this, lets see them one by one:
const myObject = {_x000D_
"employeeid": "160915848",_x000D_
"firstName": "tet",_x000D_
"lastName": "test",_x000D_
"email": "[email protected]",_x000D_
"country": "Brasil",_x000D_
"currentIndustry": "aaaaaaaaaaaaa",_x000D_
"otherIndustry": "aaaaaaaaaaaaa",_x000D_
"currentOrganization": "test",_x000D_
"salary": "1234567"_x000D_
};_x000D_
_x000D_
delete myObject['currentIndustry'];_x000D_
// OR delete myObject.currentIndustry;_x000D_
_x000D_
console.log(myObject);
_x000D_
let myObject = {_x000D_
"employeeid": "160915848",_x000D_
"firstName": "tet",_x000D_
"lastName": "test",_x000D_
"email": "[email protected]",_x000D_
"country": "Brasil",_x000D_
"currentIndustry": "aaaaaaaaaaaaa",_x000D_
"otherIndustry": "aaaaaaaaaaaaa",_x000D_
"currentOrganization": "test",_x000D_
"salary": "1234567"_x000D_
};_x000D_
_x000D_
myObject.currentIndustry = undefined;_x000D_
myObject = JSON.parse(JSON.stringify(myObject));_x000D_
_x000D_
console.log(myObject);
_x000D_
const myObject = {_x000D_
"employeeid": "160915848",_x000D_
"firstName": "tet",_x000D_
"lastName": "test",_x000D_
"email": "[email protected]",_x000D_
"country": "Brasil",_x000D_
"currentIndustry": "aaaaaaaaaaaaa",_x000D_
"otherIndustry": "aaaaaaaaaaaaa",_x000D_
"currentOrganization": "test",_x000D_
"salary": "1234567"_x000D_
};_x000D_
_x000D_
_x000D_
const {currentIndustry, ...filteredObject} = myObject;_x000D_
console.log(filteredObject);
_x000D_
Or if you can use omit() of underscore js library:
const filteredObject = _.omit(currentIndustry, 'myObject');
console.log(filteredObject);
When to use what??
If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.
hope this helps :)
you have to include two more jar files.
xmlbeans-2.3.0.jar and dom4j-1.6.1.jar Add try it will work.
Note: It is required for the files with .xlsx formats only, not for just .xlt formats.
You mean like:
String names[] = {"Ankit","Bohra","Xyz"};
But you can only do this in the same statement when you declare it
I would like to reiterate the same as mentioned by @Marian Zburlia above. It worked for me and would suggest the same to others.
git pull origin develop
should be followed by $ git pull --rebase
.
This will remove the comments coming up on the $ git status
after the latest pull.
Compare
echo "test" | wc
to
mkdnod apipe p
wc apipe
wc will block until
echo "test" > apipe
executes
If the databases share server, have a login that has priveleges to both of the databases, and simply have a query run similiar to:
$query = $this->db->query("
SELECT t1.*, t2.id
FROM `database1`.`table1` AS t1, `database2`.`table2` AS t2
");
Otherwise I think you might have to run the 2 queries separately and fix the logic afterwards.
babel-polyfill
(deprecated as of Babel 7.4) is required. You must also install it in order to get async/await working.
npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader
package.json
"devDependencies": {
"babel-core": "^6.0.20",
"babel-polyfill": "^6.0.16",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.babelrc
{
"presets": [ "es2015", "stage-0" ]
}
.js with async/await (sample code)
"use strict";
export default async function foo() {
var s = await bar();
console.log(s);
}
function bar() {
return "bar";
}
In the startup file
require("babel-core/register");
require("babel-polyfill");
If you are using webpack you need to put it as the first value of your entry
array in your webpack configuration file (usually webpack.config.js
), as per @Cemen comment:
module.exports = {
entry: ['babel-polyfill', './test.js'],
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel', }
]
}
};
If you want to run tests with babel then use:
mocha --compilers js:babel-core/register --require babel-polyfill
The ServletContext#getRealPath()
is intented to convert a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path.
The "/"
represents the web content root. I.e. it represents the web
folder as in the below project structure:
YourWebProject
|-- src
| :
|
|-- web
| |-- META-INF
| | `-- MANIFEST.MF
| |-- WEB-INF
| | `-- web.xml
| |-- index.jsp
| `-- login.jsp
:
So, passing the "/"
to getRealPath()
would return you the absolute disk file system path of the /web
folder of the expanded WAR file of the project. Something like /path/to/server/work/folder/some.war/
which you should be able to further use in File
or FileInputStream
.
Note that most starters don't seem to see/realize that you can actually pass the whole web content path to it and that they often use
String absolutePathToIndexJSP = servletContext.getRealPath("/") + "index.jsp"; // Wrong!
or even
String absolutePathToIndexJSP = servletContext.getRealPath("") + "index.jsp"; // Wronger!
instead of
String absolutePathToIndexJSP = servletContext.getRealPath("/index.jsp"); // Right!
Also note that even though you can write new files into it using FileOutputStream
, all changes (e.g. new files or edited files) will get lost whenever the WAR is redeployed; with the simple reason that all those changes are not contained in the original WAR file. So all starters who are attempting to save uploaded files in there are doing it wrong.
Moreover, getRealPath()
will always return null
or a completely unexpected path when the server isn't configured to expand the WAR file into the disk file system, but instead into e.g. memory as a virtual file system.
getRealPath()
is unportable; you'd better never use itUse getRealPath()
carefully. There are actually no sensible real world use cases for it. Based on my 20 years of Java EE experience, there has always been another way which is much better and more portable than getRealPath()
.
If all you actually need is to get an InputStream
of the web resource, better use ServletContext#getResourceAsStream()
instead, this will work regardless of the way how the WAR is expanded. So, if you for example want an InputStream
of index.jsp
, then do not do:
InputStream input = new FileInputStream(servletContext.getRealPath("/index.jsp")); // Wrong!
But instead do:
InputStream input = servletContext.getResourceAsStream("/index.jsp"); // Right!
Or if you intend to obtain a list of all available web resource paths, use ServletContext#getResourcePaths()
instead.
Set<String> resourcePaths = servletContext.getResourcePaths("/");
You can obtain an individual resource as URL
via ServletContext#getResource()
. This will return null
when the resource does not exist.
URL resource = servletContext.getResource(path);
Or if you intend to save an uploaded file, or create a temporary file, then see the below "See also" links.
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var x;
if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
else { x = new XMLHttpRequest(); }
function getdata() {
x.open('get', 'data1.txt', true);
x.onreadystatechange= showdata;
x.send(null);
}
function showdata() {
if(x.readyState==4) {
var el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
</script>
</head>
<body onload="getdata();showdata();">
<div id="content"></div>
</body>
</html>
You can set the width in pixels via inline styling:
<input type="text" name="text" style="width: 195px;">
You can also set the width with a visible character length:
<input type="text" name="text" size="35">
0.0.0.0/0
for all IPv4 addresses
::0/0
for all IPv6 addresses
all
to match any IP address
samehost
to match any of the server's own IP addresses
samenet
to match any address in any subnet that the server is directly connected to.
e.g.
host all all 0.0.0.0/0 md5
Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR
The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.
For example:
{ "things": ["a", "b", "c"] }
Would Unmarshal into a:
type Item struct {
Things []string
}
And not into:
type Item struct {
Things string
}
The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int
or float
field -- "1"
needs to Unmarshal into a string
, not into an int
like we saw with ShippingAdditionalCost int
That's working for me, in my country on Saturday and Sunday are non-working days.
For me is important the time of @StartDate and @EndDate.
CREATE FUNCTION [dbo].[fnGetCountWorkingBusinessDays]
(
@StartDate as DATETIME,
@EndDate as DATETIME
)
RETURNS INT
AS
BEGIN
DECLARE @res int
SET @StartDate = CASE
WHEN DATENAME(dw, @StartDate) = 'Saturday' THEN DATEADD(dd, 2, DATEDIFF(dd, 0, @StartDate))
WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN DATEADD(dd, 1, DATEDIFF(dd, 0, @StartDate))
ELSE @StartDate END
SET @EndDate = CASE
WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN DATEADD(dd, 0, DATEDIFF(dd, 0, @EndDate))
WHEN DATENAME(dw, @EndDate) = 'Sunday' THEN DATEADD(dd, -1, DATEDIFF(dd, 0, @EndDate))
ELSE @EndDate END
SET @res =
(DATEDIFF(hour, @StartDate, @EndDate) / 24)
- (DATEDIFF(wk, @StartDate, @EndDate) * 2)
SET @res = CASE WHEN @res < 0 THEN 0 ELSE @res END
RETURN @res
END
GO
If you only want non-negative integers, try:
^\d+$
Following worked for me like a charm:
Run following in your Terminal:
curl -L https://raw.github.com/git/git/master/contrib/completion/git-prompt.sh > ~/.bash_git
Open/Create bash_profile:
$ vi ~/.bash_profile
Add following to the file:
source ~/.bash_git
export PS1='\[\033[01;32m\]os \[\033[01;34m\]\w $(__git_ps1 "[%s]")\$\[\033[00m\] '
export GIT_PS1_SHOWDIRTYSTATE=1
export GIT_PS1_SHOWUPSTREAM="auto"
Finally, source it using:
$ source ~/.bash_profile
This will solve the problem of bash: __git_ps1: command not found
.
Also your prompt will change to "os ". To change "os" to something else, modify "os" string in export PS1 line.
I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!
Thus, the way I fixed it was:
apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -
Then running a new "apt-get update" worked flawlessly!
The following code send and recieve the current date and time from and to the server
//The following code is for the server application:
namespace Server
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
listener.Stop();
Console.ReadLine();
}
}
}
//this is the code for the client
namespace Client
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---data to send to the server---
string textToSend = DateTime.Now.ToString();
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
Console.ReadLine();
client.Close();
}
}
}
Try this
<head>
<style type ="text/css" >
.footer{
position: fixed;
text-align: center;
bottom: 0px;
width: 100%;
}
</style>
</head>
<body>
<div class="footer">All Rights Reserved</div>
</body>
Looks like other answers are using sorting. That's not optimal from performance point of view because it takes O(n logn)
time. It is possible to calculate median in O(n)
time instead. The generalized version of this problem is known as "n-order statistics" which means finding an element K in a set such that we have n elements smaller or equal to K and rest are larger or equal K. So 0th order statistic would be minimal element in the set (Note: Some literature use index from 1 to N instead of 0 to N-1). Median is simply (Count-1)/2
-order statistic.
Below is the code adopted from Introduction to Algorithms by Cormen et al, 3rd Edition.
/// <summary>
/// Partitions the given list around a pivot element such that all elements on left of pivot are <= pivot
/// and the ones at thr right are > pivot. This method can be used for sorting, N-order statistics such as
/// as median finding algorithms.
/// Pivot is selected ranodmly if random number generator is supplied else its selected as last element in the list.
/// Reference: Introduction to Algorithms 3rd Edition, Corman et al, pp 171
/// </summary>
private static int Partition<T>(this IList<T> list, int start, int end, Random rnd = null) where T : IComparable<T>
{
if (rnd != null)
list.Swap(end, rnd.Next(start, end+1));
var pivot = list[end];
var lastLow = start - 1;
for (var i = start; i < end; i++)
{
if (list[i].CompareTo(pivot) <= 0)
list.Swap(i, ++lastLow);
}
list.Swap(end, ++lastLow);
return lastLow;
}
/// <summary>
/// Returns Nth smallest element from the list. Here n starts from 0 so that n=0 returns minimum, n=1 returns 2nd smallest element etc.
/// Note: specified list would be mutated in the process.
/// Reference: Introduction to Algorithms 3rd Edition, Corman et al, pp 216
/// </summary>
public static T NthOrderStatistic<T>(this IList<T> list, int n, Random rnd = null) where T : IComparable<T>
{
return NthOrderStatistic(list, n, 0, list.Count - 1, rnd);
}
private static T NthOrderStatistic<T>(this IList<T> list, int n, int start, int end, Random rnd) where T : IComparable<T>
{
while (true)
{
var pivotIndex = list.Partition(start, end, rnd);
if (pivotIndex == n)
return list[pivotIndex];
if (n < pivotIndex)
end = pivotIndex - 1;
else
start = pivotIndex + 1;
}
}
public static void Swap<T>(this IList<T> list, int i, int j)
{
if (i==j) //This check is not required but Partition function may make many calls so its for perf reason
return;
var temp = list[i];
list[i] = list[j];
list[j] = temp;
}
/// <summary>
/// Note: specified list would be mutated in the process.
/// </summary>
public static T Median<T>(this IList<T> list) where T : IComparable<T>
{
return list.NthOrderStatistic((list.Count - 1)/2);
}
public static double Median<T>(this IEnumerable<T> sequence, Func<T, double> getValue)
{
var list = sequence.Select(getValue).ToList();
var mid = (list.Count - 1) / 2;
return list.NthOrderStatistic(mid);
}
Few notes:
O(n)
expected time. If you want O(n)
worse case time then there is technique to use median-of-median. While this would improve worse case performance, it degrades average case because constant in O(n)
is now larger. However if you would be calculating median mostly on very large data then its worth to look at.(Count-1)/2
in sorted array. But when you even number of element (Count-1)/2
is not an integer anymore and you have two medians: Lower median Math.Floor((Count-1)/2)
and Math.Ceiling((Count-1)/2)
. Some textbooks use lower median as "standard" while others propose to use average of two. This question becomes particularly critical for set of 2 elements. Above code returns lower median. If you wanted instead average of lower and upper then you need to call above code twice. In that case make sure to measure performance for your data to decide if you should use above code VS just straight sorting.MethodImplOptions.AggressiveInlining
attribute on Swap<T>
method for slightly improved performance.If you have configured navigation property 1-n I would recommend you to use:
var query = db.Categories // source
.SelectMany(c=>c.CategoryMaps, // join
(c, cm) => new { Category = c, CategoryMaps = cm }) // project result
.Select(x => x.Category); // select result
Much more clearer to me and looks better with multiple nested joins.
My problem, it showed an error called "The class Form1 can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file. Move the class code so that it is the first class in the file and try loading the designer again. ". So I moved the Form class to the first one and it worked. :)
In Ruby and Bash, you can use $
inside parentheses.
/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|$)
(This solution is similar to Pete Boughton's, but preserves the usage of $
, which means end of line, rather than using \z
, which means end of string.)
The mktemp(1)
man page explains it fairly well:
Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win. A safer, though still inferior, approach is to make a temporary directory using the same naming scheme. While this does allow one to guarantee that a temporary file will not be subverted, it still allows a simple denial of service attack. For these reasons it is suggested that mktemp be used instead.
In a script, I invoke mktemp something like
mydir=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")
which creates a temporary directory I can work in, and in which I can safely name the actual files something readable and useful.
mktemp
is not standard, but it does exist on many platforms. The "X"s will generally get converted into some randomness, and more will probably be more random; however, some systems (busybox ash, for one) limit this randomness more significantly than others
By the way, safe creation of temporary files is important for more than just shell scripting. That's why python has tempfile, perl has File::Temp, ruby has Tempfile, etc…
simply use:
@JsonFormat(pattern="10/04/2019")
or you can use pattern as you like for e.g: ('-' in place of '/')
Note that the variables @fname
or @ext
can be simply concatenated. This:
forfiles /S /M *.pdf /C "CMD /C REN @path @fname_old.@ext"
renames all PDF files to "filename_old.pdf"
Use this : -- SQL Server 2008 or later
SELECT U.*
FROM USERS AS U
Inner Join (
SELECT
EMail, [Status]
FROM
(
Values
('email1', 'Exist'),
('email2', 'Exist'),
('email3', 'Not Exist'),
('email4', 'Exist')
)AS TempTableName (EMail, [Status])
Where TempTableName.EMail IN ('email1','email2','email3')
) As TMP ON U.EMail = TMP.EMail
wait()
with a timeout value can wakeup upon timeout value elapsed or notify whichever is earlier (or interrupt as well),
whereas, a sleep()
wakes up on timeout value elapsed or interrupt whichever is earlier. wait()
with no timeout value will wait for ever until notified or interrupted.
You don't say what you want to do with the resulting data, but if it's general queries for development/maintenance then I'd have thought Remote Desktop to the windows server and then using the actual SQL Server tools on their would always have been a more productive option over any hacked together solution on Linux itself.
This should do what you want:
import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")
You need an additional library for code coverage, and you are going to be blown away by how powerful and easy istanbul is. Try the following, after you get your mocha tests to pass:
npm install nyc
Now, simply place the command nyc in front of your existing test command, for example:
{
"scripts": {
"test": "nyc mocha"
}
}
Use Shell "program file path file path you want to open"
.
Example:
Shell "c:\windows\system32\mspaint.exe c:users\admin\x.jpg"
You need either
A foreign key needs to uniquely identify the parent row: you currently have no way to do that because Title is not unique.
Using this regular expression you can validate different kinds of Date/Time samples, just a little change is needed.
^\d\d\d\d/(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01]) (00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$
-->validate this: 2018/7/12 13:00:00
for your format you cad change it to:
^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[0-2])/\d\d$
--> validates this: 11/12/98
Look out for this pitfal: http://www.vertstudios.com/blog/avoiding-ajax-newline-pitfall/
Searched several houres before I found there were some linebreaks in the included files.
For me waitKey() with number greater than 0 worked
cv2.waitKey(1)
It turns out there's more than one problem with that code. A fragment cannot be declared that way, inside the same java file as the activity but not as a public inner class. The framework expects the fragment's constructor (with no parameters) to be public and visible. Moving the fragment into the Activity as an inner class, or creating a new java file for the fragment fixes that.
The second issue is that when you're adding a fragment this way, you must pass a reference to the fragment's containing view, and that view must have a custom id. Using the default id will crash the app. Here's the updated code:
public class DebugExampleTwo extends Activity {
private static final int CONTENT_VIEW_ID = 10101010;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frame = new FrameLayout(this);
frame.setId(CONTENT_VIEW_ID);
setContentView(frame, new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
if (savedInstanceState == null) {
Fragment newFragment = new DebugExampleTwoFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(CONTENT_VIEW_ID, newFragment).commit();
}
}
public static class DebugExampleTwoFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
EditText v = new EditText(getActivity());
v.setText("Hello Fragment!");
return v;
}
}
}
What you describe isn't overriding. If you don't specify a default constructor, the compiler will create a default constructor. If it's a subclass, it will call the default parent constructor(super()), it will also initialize all instance variables to a default value determined by the type's default value(0 for numeric types, false for booleans, or null for objects).
Overriding happens when a subclass has the same name, number/type of parameters, and the same return type as an instance method of the superclass. In this case, the subclass will override the superclass's method. Information on overriding here.
With version 1.7 of the official 10gen driver, this is the current (non-obsolete) API:
const string uri = "mongodb://localhost/mydb";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
var collection = db.GetCollection("mycollection");
A loading indicator is simply an animated image (.gif) that is displayed until the completed event is called on the AJAX request. http://ajaxload.info/ offers many options for generating loading images that you can overlay on your modals. To my knowledge, Bootstrap does not provide the functionality built-in.
By the way, in the question above:
For:
Hello, my name is bob
Find part:
my name is (\w)+
With replace part:
my name used to be \1
Would return:
Hello, my name used to be b
Change find part to:
my name is (\w+)
And replace will be what you expect:
Hello, my name used to be bob
While (\w)+ will match "bob", it is not the grouping you want for replacement.
Richard's answer is correct. Alternatively you can also create a MappingJsonFactory
(in org.codehaus.jackson.map
) which knows where to find ObjectMapper
. The error you got was because the regular JsonFactory
(from core
package) has no dependency to ObjectMapper
(which is in the mapper
package).
But usually you just use ObjectMapper
and do not worry about JsonParser
or other low level components -- they will just be needed if you want to data-bind parts of stream, or do low-level handling.
1) To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
2) To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
3) To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
4) To remove white space at both ends:
df.columns = df.columns.str.strip()
5) To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7) To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
As pointed out already, most standard implementations of List
are serializable. However you have to ensure that the objects referenced/contained within the list are also serializable.
You've got about these four possibilities:
Remote files. This needs allow_url_fopen
to be enabled in php.ini, but it's the easiest method.
Alternatively you could use cURL if your PHP installation supports it. There's even an example.
And if you really want to do it manually use the HTTP module.
Don't even try to use sockets directly.
We can override +
. If unary +
is used and its argument is itself an unary +
call, then increment the relevant variable in the calling environment.
`+` <- function(e1,e2){
# if unary `+`, keep original behavior
if(missing(e2)) {
s_e1 <- substitute(e1)
# if e1 (the argument of unary +) is itself an unary `+` operation
if(length(s_e1) == 2 &&
identical(s_e1[[1]], quote(`+`)) &&
length(s_e1[[2]]) == 1) {
# increment value in parent environment
eval.parent(substitute(e1 <- e1 + 1, list(e1 = s_e1[[2]])))
# else unary `+` should just return it's input
} else e1
# if binary `+`, keep original behavior
} else .Primitive("+")(e1, e2)
}
x <- 10
++x
x
# [1] 11
other operations don't change :
x + 2
# [1] 13
x ++ 2
# [1] 13
+x
# [1] 11
x
# [1] 11
Don't do it though, as you'll slow down everything. Or do it in another environment and make sure you don't have big loops on these instructions.
You can also just do this :
`++` <- function(x) eval.parent(substitute(x <- x + 1))
a <- 1
`++`(a)
a
# [1] 2
Undefined offset means there's an empty array key for example:
$a = array('Felix','Jon','Java');
// This will result in an "Undefined offset" because the size of the array
// is three (3), thus, 0,1,2 without 3
echo $a[3];
You can solve the problem using a loop (while):
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
// Increase count by 1, thus, $i=1
$i++;
$groupname[$i] = base64_decode(base64_decode($row['groupname']));
// Set the first position of the array to null or empty
$groupname[0] = "";
}
$('#cloneDiv').click(function(){_x000D_
_x000D_
_x000D_
// get the last DIV which ID starts with ^= "klon"_x000D_
var $div = $('div[id^="klon"]:last');_x000D_
_x000D_
// Read the Number from that DIV's ID (i.e: 3 from "klon3")_x000D_
// And increment that number by 1_x000D_
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;_x000D_
_x000D_
// Clone it and assign the new ID (i.e: from num 4 to ID "klon4")_x000D_
var $klon = $div.clone().prop('id', 'klon'+num );_x000D_
_x000D_
// Finally insert $klon wherever you want_x000D_
$div.after( $klon.text('klon'+num) );_x000D_
_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>_x000D_
_x000D_
<button id="cloneDiv">CLICK TO CLONE</button> _x000D_
_x000D_
<div id="klon1">klon1</div>_x000D_
<div id="klon2">klon2</div>
_x000D_
Say you have many elements with IDs like klon--5
but scrambled (not in order). Here we cannot go for :last
or :first
, therefore we need a mechanism to retrieve the highest ID:
const $all = $('[id^="klon--"]');_x000D_
const maxID = Math.max.apply(Math, $all.map((i, el) => +el.id.match(/\d+$/g)[0]).get());_x000D_
const nextId = maxID + 1;_x000D_
_x000D_
console.log(`New ID is: ${nextId}`);
_x000D_
<div id="klon--12">12</div>_x000D_
<div id="klon--34">34</div>_x000D_
<div id="klon--8">8</div>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
_x000D_
The first server block in the nginx config is the default for all requests that hit the server for which there is no specific server block.
So in your config, assuming your real domain is REAL.COM, when a user types that in, it will resolve to your server, and since there is no server block for this setup, the server block for FAKE.COM, being the first server block (only server block in your case), will process that request.
This is why proper Nginx configs have a specific server block for defaults before following with others for specific domains.
# Default server
server {
return 404;
}
server {
server_name domain_1;
[...]
}
server {
server_name domain_2;
[...]
}
etc
It seems some users are a bit confused by this example and think it is limited to a single conf file etc.
Please note that the above is a simple example for the OP to develop as required.
I personally use separate vhost conf files with this as so (CentOS/RHEL):
http {
[...]
# Default server
server {
return 404;
}
# Other servers
include /etc/nginx/conf.d/*.conf;
}
/etc/nginx/conf.d/
will contain domain_1.conf, domain_2.conf... domain_n.conf which will be included after the server block in the main nginx.conf file which will always be the first and will always be the default unless it is overridden it with the default_server directive elsewhere.
The alphabetical order of the file names of the conf files for the other servers becomes irrelevant in this case.
In addition, this arrangement gives a lot of flexibility in that it is possible to define multiple defaults.
In my specific case, I have Apache listening on Port 8080 on the internal interface only and I proxy PHP and Perl scripts to Apache.
However, I run two separate applications that both return links with ":8080" in the output html attached as they detect that Apache is not running on the standard Port 80 and try to "help" me out.
This causes an issue in that the links become invalid as Apache cannot be reached from the external interface and the links should point at Port 80.
I resolve this by creating a default server for Port 8080 to redirect such requests.
http {
[...]
# Default server block for undefined domains
server {
listen 80;
return 404;
}
# Default server block to redirect Port 8080 for all domains
server {
listen my.external.ip.addr:8080;
return 301 http://$host$request_uri;
}
# Other servers
include /etc/nginx/conf.d/*.conf;
}
As nothing in the regular server blocks listens on Port 8080, the redirect default server block transparently handles such requests by virtue of its position in nginx.conf.
I actually have four of such server blocks and this is a simplified use case.
Using LINQ's Union
Enumerable.Union(ListA,ListB);
or
ListA.Union(ListB);
The reason is your current ruby environment, you got a different version of bundler with the version in Gemfile.lock
.
Gemfile.lock
, this won't break anything if there is some incampatibly thing happened.Gemfile.lock
, and run bundle install
.In my scenario, there was no process blocking the database under sp_who2. However, we discovered because the database is much larger than our other databases that pending processes were still running which is why the database under the availability group still displayed as red/offline after we tried to 'resume data'by right clicking the paused database.
To check if you still have processes running just execute this command: select percent complete from sys.dm_exec_requests where percent_complete > 0
# Usage: template your_file.conf.template > your_file.conf
template() {
local IFS line
while IFS=$'\n\r' read -r line ; do
line=${line//\\/\\\\} # escape backslashes
line=${line//\"/\\\"} # escape "
line=${line//\`/\\\`} # escape `
line=${line//\$/\\\$} # escape $
line=${line//\\\${/\${} # de-escape ${ - allows variable substitution: ${var} ${var:-default_value} etc
# to allow arithmetic expansion or command substitution uncomment one of following lines:
# line=${line//\\\$\(/\$\(} # de-escape $( and $(( - allows $(( 1 + 2 )) or $( command ) - UNSECURE
# line=${line//\\\$\(\(/\$\(\(} # de-escape $(( - allows $(( 1 + 2 ))
eval "echo \"${line}\"";
done < "$1"
}
This is the pure bash function adjustable to your liking, used in production and should not break on any input. If it breaks - let me know.
I think the most pythonic way to do this for me, will be
elif var in [80,443] + range(1024,65535):
although it could take a little time and memory (it's generating numbers from 1024 to 65535). If there's a problem with that, I'll do:
elif 1024 <= var <= 65535 or var in [80,443]:
Or you can do this using HTML5. Simply with
<a href="example.csv" download>download not open it</a>
This works in MSSQL and MySQL:
SELECT *
FROM Village
WHERE CastleType LIKE '%foo%';
My friend, you need to create those corresponding branches locally first, in order to check-out to those other two branches, using this line of code
git branch test-branch
and
git branch change-the-title
then only you will be able to do git checkout to those branches
Also after creating each branch, take latest changes of those particular branches by using git pull origin branch_name as shown in below code
git branch test-branch
git checkout test-branch
git pull origin test-branch
and for other branch named change-the-title run following code =>
git branch change-the-title
git checkout change-the-title
git pull origin change-the-title
Happy programming :)
Since you are asking for space between
, I would add an override to the last item to get rid of the extra margin there:
li {_x000D_
background: red;_x000D_
margin-bottom: 40px;_x000D_
}_x000D_
_x000D_
li:last-child {_x000D_
margin-bottom: 0px;_x000D_
}_x000D_
_x000D_
ul {_x000D_
background: silver;_x000D_
padding: 1px; _x000D_
padding-left: 40px;_x000D_
}
_x000D_
<ul>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
</ul>
_x000D_
The result of it might not be visual at all times, because of margin-collapsing and stuff... in the example snippets I've included, I've added a small 1px padding
to the ul
-element to prevent the collapsing. Try removing the li:last-child
-rule, and you'll see that the last item now extends the size of the ul
-element.
You need to set
WindowStyle="None"
, AllowsTransparency="True"
and optionally ResizeMode="NoResize"
and then set the Style
property of the window to your custom window style, where you design the appearance of the window (title bar, buttons, border) to anything you want and display the window contents in a ContentPresenter
.
This seems to be a good article on how you can achieve this, but there are many other articles on the internet.
The point of JSON is that it is completely dynamic and flexible. Bend it to whatever whim you would like, because it's just a set of serialized JavaScript objects and arrays, rooted in a single node.
What the type of the rootnode is is up to you, what it contains is up to you, whether you send metadata along with the response is up to you, whether you set the mime-type to application/json
or leave it as text/plain
is up to you (as long as you know how to handle the edge cases).
Build a lightweight schema that you like.
Personally, I've found that analytics-tracking and mp3/ogg serving and image-gallery serving and text-messaging and network-packets for online gaming, and blog-posts and blog-comments all have very different requirements in terms of what is sent and what is received and how they should be consumed.
So the last thing I'd want, when doing all of that, is to try to make each one conform to the same boilerplate standard, which is based on XML2.0 or somesuch.
That said, there's a lot to be said for using schemas which make sense to you and are well thought out.
Just read some API responses, note what you like, criticize what you don't, write those criticisms down and understand why they rub you the wrong way, and then think about how to apply what you learned to what you need.
db.query(
TABLE_NAME,
new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO },
TABLE_ROW_ID + "=" + rowID,
null, null, null, null, null
);
TABLE_ROW_ID + "=" + rowID
, here =
is the where
clause. To select all values you will have to give all column names:
or you can use a raw query like this
db.rawQuery("SELECT * FROM permissions_table WHERE name = 'Comics' ", null);
and here is a good tutorial for database.
I got around this with len()
and a simple if/else
statement.
List elements will come back as an integer when wrapped in len()
(1 for present, 0 for absent)
l = []
print(len(l)) # Prints 0
if len(l) == 0:
print("Element is empty")
else:
print("Element is NOT empty")
Output:
Element is empty
To avoid the UnauthorizedAccessException
, I use:
var files = GetFiles(@"C:\", "*.*", SearchOption.AllDirectories);
foreach (var file in files)
{
Console.WriteLine($"{file}");
}
public static IEnumerable<string> GetFiles(string path, string searchPattern, SearchOption searchOption)
{
var foldersToProcess = new List<string>()
{
path
};
while (foldersToProcess.Count > 0)
{
string folder = foldersToProcess[0];
foldersToProcess.RemoveAt(0);
if (searchOption.HasFlag(SearchOption.AllDirectories))
{
//get subfolders
try
{
var subfolders = Directory.GetDirectories(folder);
foldersToProcess.AddRange(subfolders);
}
catch (Exception ex)
{
//log if you're interested
}
}
//get files
var files = new List<string>();
try
{
files = Directory.GetFiles(folder, searchPattern, SearchOption.TopDirectoryOnly).ToList();
}
catch (Exception ex)
{
//log if you're interested
}
foreach (var file in files)
{
yield return file;
}
}
}
<?php
function createThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth) {
$explode = explode(".", $imageName);
$filetype = $explode[1];
if ($filetype == 'jpg') {
$srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
} else
if ($filetype == 'jpeg') {
$srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
} else
if ($filetype == 'png') {
$srcImg = imagecreatefrompng("$imageDirectory/$imageName");
} else
if ($filetype == 'gif') {
$srcImg = imagecreatefromgif("$imageDirectory/$imageName");
}
$origWidth = imagesx($srcImg);
$origHeight = imagesy($srcImg);
$ratio = $origWidth / $thumbWidth;
$thumbHeight = $origHeight / $ratio;
$thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $origWidth, $origHeight);
if ($filetype == 'jpg') {
imagejpeg($thumbImg, "$thumbDirectory/$imageName");
} else
if ($filetype == 'jpeg') {
imagejpeg($thumbImg, "$thumbDirectory/$imageName");
} else
if ($filetype == 'png') {
imagepng($thumbImg, "$thumbDirectory/$imageName");
} else
if ($filetype == 'gif') {
imagegif($thumbImg, "$thumbDirectory/$imageName");
}
}
?>
This is a very good thumbnail script =) Here's an example:
$path = The path to the folder where the original picture is. $name = The filename of the file you want to make a thumbnail of. $thumbpath = The path to the directory where you want the thumbnail to be saved into. $maxwidth = the maximum width of the thumbnail in PX eg. 100 (wich will be 100px).
createThumbnail($path, $name, $thumbpath, $maxwidth);
Set up a device for development https://developer.android.com/studio/run/device.html#setting-up
Enable developer options and debugging https://developer.android.com/studio/debug/dev-options.html#enable
Optional
For those working in Visual Studio
simply add the include
, Lib
and libs
directories to the Include Directories
and Library Directories
under
Projects Properties -> Configuration Properties > VC++ Directories
:
For example I have Anaconda3
on my system and working with Visual Studio 2015
This is how the settings looks like (note the Include and Library directories) :
As also pointed out by bossi setting PYTHONPATH
in your user Environment Variables
section seems necessary.
a sample input can be like this (in my case):
C:\Users\Master\Anaconda3\Lib;C:\Users\Master\Anaconda3\libs;C:\Users\Master\Anaconda3\Lib\site-packages;C:\Users\Master\Anaconda3\DLLs
is necessary it seems.
Also, you need to restart Visual Studio
after you set up the PYTHONPATH
in your user Environment Variables for the changes to take effect.
Also note that :
Make sure the
PYTHONHOME
environment variable is set to the Python interpreter you want to use. The C++ projects in Visual Studio rely on this variable to locate files such aspython.h
, which are used when creating a Python extension.
Based on Lucio's code, I made a module. It will return an away with all the files with specific extensions under the one. Just post it here in case anybody needs it.
var path = require('path'),
fs = require('fs');
/**
* Find all files recursively in specific folder with specific extension, e.g:
* findFilesInDir('./project/src', '.html') ==> ['./project/src/a.html','./project/src/build/index.html']
* @param {String} startPath Path relative to this file or other file which requires this files
* @param {String} filter Extension name, e.g: '.html'
* @return {Array} Result files with path string in an array
*/
function findFilesInDir(startPath,filter){
var results = [];
if (!fs.existsSync(startPath)){
console.log("no dir ",startPath);
return;
}
var files=fs.readdirSync(startPath);
for(var i=0;i<files.length;i++){
var filename=path.join(startPath,files[i]);
var stat = fs.lstatSync(filename);
if (stat.isDirectory()){
results = results.concat(findFilesInDir(filename,filter)); //recurse
}
else if (filename.indexOf(filter)>=0) {
console.log('-- found: ',filename);
results.push(filename);
}
}
return results;
}
module.exports = findFilesInDir;
int64
(from numpy) to int
.For example, if variable x
is a int64:
int(x)
If is array of int64:
map(int, x)
Take and store image in desired folder
//Global Variables
private static final int CAMERA_IMAGE_REQUEST = 101;
private String imageName;
Take picture function
public void captureImage() {
// Creating folders for Image
String imageFolderPath = Environment.getExternalStorageDirectory().toString()
+ "/AutoFare";
File imagesFolder = new File(imageFolderPath);
imagesFolder.mkdirs();
// Generating file name
imageName = new Date().toString() + ".png";
// Creating image here
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imageFolderPath, imageName)));
startActivityForResult(takePictureIntent,
CAMERA_IMAGE_REQUEST);
}
Broadcast new image added otherwise pic will not be visible in image gallery
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == CAMERA_IMAGE_REQUEST) {
Toast.makeText(getActivity(), "Success",
Toast.LENGTH_SHORT).show();
//Scan new image added
MediaScannerConnection.scanFile(getActivity(), new String[]{new File(Environment.getExternalStorageDirectory()
+ "/AutoFare/" + imageName).getPath()}, new String[]{"image/png"}, null);
// Work in few phones
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(Environment.getExternalStorageDirectory()
+ "/AutoFare/" + imageName)));
} else {
getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(Environment.getExternalStorageDirectory()
+ "/AutoFare/" + imageName)));
}
} else {
Toast.makeText(getActivity(), "Take Picture Failed or canceled",
Toast.LENGTH_SHORT).show();
}
}
Permissions
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I've just had this problem. after a day of checking finally I've got the answer with that The mysql.sock file is created when MariaDB starts and is removed when MariaDB is shutdown. It won't exist if MariaDB is not running. maybe you didn't install MariaDB. YOU COULD FOLLOW THE INSTRUCTION BELOW: https://www.linode.com/docs/databases/mariadb/how-to-install-mariadb-on-centos-7 BEST
I had this problem and found that removing the following folder helped, even with the non-Express edition.Express:
C:\Users\<user>\Documents\IISExpress
For SOA system architecture, I use the SOACP Visio stencil. It provides the symbols that are used in Thomas Erl's SOA book series.
I use the Visio Network and Database stencils to model most other requirements.
the simplest way:
sudo docker cp path/on/your/machine adam_ubuntu:/root/path_in_container
Note putting into the root path if you are copying something that needs to be picked up by the root using ~.
AndroidStudioFrontScreenI simply double clicked the Android dmg install file that I saved on the hard drive and when the initial screen came up I dragged the icon for Android Studio into the Applications folder, now I know where it is!!! Also when you run it, be sure to right click the Android Studio while on the Dock and select "Options" -> "Keep on Dock". Everything else works. Dr. Roger Webster
I think you could do:
$('#google_translate_element').find('*').each(function(){
$(this).unbind('click');
});
but it would cause a lot of overhead
The xargs
command takes white space characters (tabs, spaces, new lines) as delimiters.
You can narrow it down only for the new line characters ('\n') with -d
option like this:
ls *.mp3 | xargs -d '\n' mplayer
It works only with GNU xargs.
For BSD systems, use the -0
option like this:
ls *.mp3 | xargs -0 mplayer
This method is simpler and works with the GNU xargs as well.
For MacOS:
ls *.mp3 | tr \\n \\0 | xargs -0 mplayer
Here is production code which may help you.
Package.json
{
"name": "node-mysql",
"version": "0.0.1",
"dependencies": {
"express": "^4.10.6",
"mysql": "^2.5.4"
}
}
Here is Server file.
var express = require("express");
var mysql = require('mysql');
var app = express();
var pool = mysql.createPool({
connectionLimit : 100, //important
host : 'localhost',
user : 'root',
password : '',
database : 'address_book',
debug : false
});
function handle_database(req,res) {
pool.getConnection(function(err,connection){
if (err) {
connection.release();
res.json({"code" : 100, "status" : "Error in connection database"});
return;
}
console.log('connected as id ' + connection.threadId);
connection.query("select * from user",function(err,rows){
connection.release();
if(!err) {
res.json(rows);
}
});
connection.on('error', function(err) {
res.json({"code" : 100, "status" : "Error in connection database"});
return;
});
});
}
app.get("/",function(req,res){-
handle_database(req,res);
});
app.listen(3000);
Reference : https://codeforgeek.com/2015/01/nodejs-mysql-tutorial/
You can simply place a forward declaration of your second()
function in your main.cpp
above main()
. If your second.cpp
has more than one function and you want all of it in main()
, put all the forward declarations of your functions in second.cpp
into a header file and #include
it in main.cpp
.
Like this-
Second.h:
void second();
int third();
double fourth();
main.cpp:
#include <iostream>
#include "second.h"
int main()
{
//.....
return 0;
}
second.cpp:
void second()
{
//...
}
int third()
{
//...
return foo;
}
double fourth()
{
//...
return f;
}
Note that: it is not necessary to #include "second.h"
in second.cpp
. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.
You can define a method in spec_helper.rb that sends a message both to Rails.logger.info and to puts and use that for debugging:
def log_test(message)
Rails.logger.info(message)
puts message
end
Use dbms_lob.instr and dbms_lob.substr, just like regular InStr and SubstStr functions.
Look at simple example:
SQL> create table t_clob(
2 id number,
3 cl clob
4 );
Tabela zosta¦a utworzona.
SQL> insert into t_clob values ( 1, ' xxxx abcd xyz qwerty 354657 [] ' );
1 wiersz zosta¦ utworzony.
SQL> declare
2 i number;
3 begin
4 for i in 1..400 loop
5 update t_clob set cl = cl || ' xxxx abcd xyz qwerty 354657 [] ';
6 end loop;
7 update t_clob set cl = cl || ' CALCULATION=[N]NEW.PRODUCT_NO=[T9856] OLD.PRODUCT_NO=[T9852].... -- with other text ';
8 for i in 1..400 loop
9 update t_clob set cl = cl || ' xxxx abcd xyz qwerty 354657 [] ';
10 end loop;
11 end;
12 /
Procedura PL/SQL zosta¦a zako?czona pomytlnie.
SQL> commit;
Zatwierdzanie zosta¦o uko?czone.
SQL> select length( cl ) from t_clob;
LENGTH(CL)
----------
25717
SQL> select dbms_lob.instr( cl, 'NEW.PRODUCT_NO=[' ) from t_clob;
DBMS_LOB.INSTR(CL,'NEW.PRODUCT_NO=[')
-------------------------------------
12849
SQL> select dbms_lob.substr( cl, 5,dbms_lob.instr( cl, 'NEW.PRODUCT_NO=[' ) + length( 'NEW.PRODUCT_NO=[') ) new_product
2 from t_clob;
NEW_PRODUCT
--------------------------------------------------------------------------------
T9856