The configuration file is called applicationhost.config. It's stored here:
My Documents > IIS Express > config
usually, but not always, one of these paths will work
%userprofile%\documents\iisexpress\config\applicationhost.config
%userprofile%\my documents\iisexpress\config\applicationhost.config
Update for VS2019
If you're using Visual Studio 2019+ check this path:
$(solutionDir)\.vs\{projectName}\config\applicationhost.config
Update for VS2015 (credit: @Talon)
If you're using Visual Studio 2015-2017 check this path:
$(solutionDir)\.vs\config\applicationhost.config
In Visual Studio 2015+ you can also configure which applicationhost.config file is used by altering the <UseGlobalApplicationHostFile>true|false</UseGlobalApplicationHostFile>
setting in the project file (eg: MyProject.csproj). (source: MSDN forum)
In addition to the answer by @nologo, I also had to use IIS. So I changed the
<UseIIS>True</UseIIS>
to 'False' first.
The ConverterParameter
property can not be bound because it is not a dependency property.
Since Binding
is not derived from DependencyObject
none of its properties can be dependency properties. As a consequence, a Binding can never be the target object of another Binding.
There is however an alternative solution. You could use a MultiBinding
with a multi-value converter instead of a normal Binding:
<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
<Setter.Value>
<MultiBinding Converter="{StaticResource AccessLevelToVisibilityConverter}">
<Binding Path="Tag" RelativeSource="{RelativeSource Mode=FindAncestor,
AncestorType=UserControl}"/>
<Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
The multi-value converter gets an array of source values as input:
public class AccessLevelToVisibilityConverter : IMultiValueConverter
{
public object Convert(
object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.All(v => (v is bool && (bool)v))
? Visibility.Visible
: Visibility.Hidden;
}
public object[] ConvertBack(
object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
please make sure following changes should be uncommented, which I did and got succeed in centos7
vi /etc/ssh/sshd_config
1.PubkeyAuthentication yes
2.PasswordAuthentication yes
3.GSSAPIKeyExchange no
4.GSSAPICleanupCredentials no
systemctl restart sshd
ssh-keygen
chmod 777 /root/.ssh/id_rsa.pub
ssh-copy-id -i /root/.ssh/id_rsa.pub user@ipaddress
thank you all and good luck
You can use arg(), as follow:
double dbl = 0.25874601;
QString str = QString("%1").arg(dbl);
This overcomes the problem of: "Fixed precision" at the other functions like: setNum() and number(), which will generate random numbers to complete the defined precision
What about:
git reset
back to the last commit before you started making changes.git pull
to re-pull just the remote changes you threw away with the reset.Or will that explode when you try to re-merge the branch?
Bill the user: "Hey Jimmy, show me that report"
Jimmy the SP: "Hey, I'm not sure who you are yet. We have a process here so you go get yourself verified with Bob the IdP first. I trust him."
Bob the IdP: "I see Jimmy sent you here. Please give me your credentials."
Bill the user: "Hi I'm Bill. Here are my credentials."
Bob the IdP: "Hi Bill. Looks like you check out."
Bob the IdP: "Hey Jimmy. This guy Bill checks out and here's some additional information about him. You do whatever you want from here."
Jimmy the SP: "Ok cool. Looks like Bill is also in our list of known guests. I'll let Bill in."
Bill the user: "Hey Bob. I want to go to Jimmy's place. Security is tight over there."
Bob the IdP: "Hey Jimmy. I trust Bill. He checks out and here's some additional information about him. You do whatever you want from here."
Jimmy the SP: "Ok cool. Looks like Bill is also in our list of known guests. I'll let Bill in."
I go into more detail here, but still keeping things simple: https://jorgecolonconsulting.com/saml-sso-in-simple-terms/.
You can always check the output of path_helpers
in console. Just use the helper with app
app.post_path(3)
#=> "/posts/3"
app.posts_path
#=> "/posts"
app.posts_url
#=> "http://www.example.com/posts"
With C++11 for measuring the execution time of a piece of code, we can use the now() function:
auto start = chrono::steady_clock::now();
// Insert the code that will be timed
auto end = chrono::steady_clock::now();
// Store the time difference between start and end
auto diff = end - start;
If you want to print the time difference between start and end in the above code, you could use:
cout << chrono::duration <double, milli> (diff).count() << " ms" << endl;
If you prefer to use nanoseconds, you will use:
cout << chrono::duration <double, nano> (diff).count() << " ns" << endl;
The value of the diff variable can be also truncated to an integer value, for example, if you want the result expressed as:
diff_sec = chrono::duration_cast<chrono::nanoseconds>(diff);
cout << diff_sec.count() << endl;
For more info click here
Building onto answer from @zeusstl, for multiple images uploaded:
function img_resize()
{
$input = 'input-upload-img1'; // Name of input
$maxDim = 400;
foreach ($_FILES[$input]['tmp_name'] as $file_name){
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
$target_filename = $file_name;
$ratio = $width/$height;
if( $ratio > 1) {
$new_width = $maxDim;
$new_height = $maxDim/$ratio;
} else {
$new_width = $maxDim*$ratio;
$new_height = $maxDim;
}
$src = imagecreatefromstring( file_get_contents( $file_name ) );
$dst = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagedestroy( $src );
imagepng( $dst, $target_filename ); // adjust format as needed
imagedestroy( $dst );
}
}
}
The assertion libraries in Mocha work by throwing an error if the assertion was not correct. Throwing an error results in a rejected promise, even when thrown in the executor function provided to the catch
method.
.catch((error) => {
assert.isNotOk(error,'Promise error');
done();
});
In the above code the error
objected evaluates to true
so the assertion library throws an error... which is never caught. As a result of the error the done
method is never called. Mocha's done
callback accepts these errors, so you can simply end all promise chains in Mocha with .then(done,done)
. This ensures that the done method is always called and the error would be reported the same way as when Mocha catches the assertion's error in synchronous code.
it('should transition with the correct event', (done) => {
const cFSM = new CharacterFSM({}, emitter, transitions);
let timeout = null;
let resolved = false;
new Promise((resolve, reject) => {
emitter.once('action', resolve);
emitter.emit('done', {});
timeout = setTimeout(() => {
if (!resolved) {
reject('Timedout!');
}
clearTimeout(timeout);
}, 100);
}).then(((state) => {
resolved = true;
assert(state.action === 'DONE', 'should change state');
})).then(done,done);
});
I give credit to this article for the idea of using .then(done,done) when testing promises in Mocha.
Put the div in another div and set the parent div's style to position:relative;
Then on the child div set the following CSS properties: position:absolute; bottom:0;
Once I also got that same type of error.
I.E:
C:\oracle\product\10.2.0\db_2>SQLPLUS SYS AS SYSDBA
Error 6 initializing SQL*Plus
Message file sp1<lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory
This error is occurring as the home path is not correctly set. To rectify this, if you are using Windows, run the below query:
C:\oracle\product\10.2.0\db_2>SET ORACLE_HOME=C:\oracle\product\10.2.0\db_2
C:\oracle\product\10.2.0\db_2>SQLPLUS SYS AS SYSDBA
SQL*Plus: Release 10.2.0.3.0 - Production on Tue Apr 16 13:17:42 2013
Copyright (c) 1982, 2006, Oracle. All Rights Reserved.
Or if you are using Linux, then replace set
with export
for the above command like so:
C:\oracle\product\10.2.0\db_2>EXPORT ORACLE_HOME='C:\oracle\product\10.2.0\db_2'
C:\oracle\product\10.2.0\db_2>SQLPLUS SYS AS SYSDBA
SQL*Plus: Release 10.2.0.3.0 - Production on Tue Apr 16 13:17:42 2013
Copyright (c) 1982, 2006, Oracle. All Rights Reserved.
Well array.length
should do the trick or not? something like, i mean you don't need to know the index range if you just read it..
var arrayContainingObjects = [];
for (var i = 0; i < arrayContainingYourItems.length; i++){
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
Maybe i didn't understand your Question correctly, but you should be able to get the length of your Array this way and transforming them into objects. Daniel kind of gave the same answer to be honest. You could just save your array-length in to his variable and it would be done.
IF and this should not happen in my opinion you can't get your Array-length. As you said w/o getting the index number you could do it like this:
var arrayContainingObjects = [];
for (;;){
try{
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
}
catch(err){
break;
}
It is the not-nice version of the one above but the loop would execute until you "run" out of the index range.
It's an iterator returned by the filter function.
If you want a list, just do
list(filter(f, range(2, 25)))
Nonetheless, you can just iterate over this object with a for
loop.
for e in filter(f, range(2, 25)):
do_stuff(e)
In my case it was due to passing in \r\n characters inside TestCase's. Not sure why it's causing intermittent issues, as it works most of the time. But if I remove \r\n the test is never inconclusive:
[TestCase("test\r\n1,2\r\n3,4", 1, 2)]
public void My_Test(string message, double latitude, double longitude)
This can get you selector path of clicked HTML element-
$("*").on("click", function() {
let selectorPath = $(this).parents().map(function () {return this.tagName;}).get().reverse().join("->");
alert(selectorPath);
return false;
});
It depends on the version of Windows 10 you're using. Starting with Windows 10 Anniversary Update version 1607, Sticky Notes is storing its data in the following directory:
%UserProfile%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe
If your Windows 10 has an older version, it is storing the date in the following directory:
%UserProfile%\AppData\Roaming\Microsoft\StickyNotes\StickyNotes.snt
Note: You have to specify class name along with packages as given below.
<suite name="testNGLearning">
<test name="simpleTest">
<classes>
<class name="testngTests.TestNGSimpleTest" />
<class name="testngTests.TestMessageUtil" />
</classes>
</test>
</suite>
Add an nested document in solr very complex and nested data search also very complex. but Elastic Search easy to add nested document and search
Something likes this
public void testPrintOut() {
int val1 = 8;
String val2 = "$951.23";
String val3 = "$215.92";
String val4 = "$198,301.22";
System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
val1 = 9;
val2 = "$950.19";
val3 = "$216.95";
val4 = "$198,084.26";
System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
}
If you doing from windows folder, I mean if you are using the kafka from windows machine
kafka-console-consumer.bat --bootstrap-server localhost:9092 --<topic-name> test --from-beginning
I use PyCharm (same pydev engine as eclipse). Really helps me to visually be able to step through my code and see what is happening.
I construct my own class, and then call it from my activity, overriding small methods like showAtLocation. I've found its easier when I have 4 to 5 popups in my activity to do this.
public class ToggleValues implements OnClickListener{
private View pView;
private LayoutInflater inflater;
private PopupWindow pop;
private Button one, two, three, four, five, six, seven, eight, nine, blank;
private ImageButton eraser;
private int selected = 1;
private Animation appear;
public ToggleValues(int id, Context c, int screenHeight){
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
pop = new PopupWindow(inflater.inflate(id, null, false), 265, (int)(screenHeight * 0.45), true);
pop.setBackgroundDrawable(c.getResources().getDrawable(R.drawable.alpha_0));
pView = pop.getContentView();
appear = AnimationUtils.loadAnimation(c, R.anim.appear);
one = (Button) pView.findViewById(R.id.one);
one.setOnClickListener(this);
two = (Button) pView.findViewById(R.id.two);
two.setOnClickListener(this);
three = (Button) pView.findViewById(R.id.three);
three.setOnClickListener(this);
four = (Button) pView.findViewById(R.id.four);
four.setOnClickListener(this);
five = (Button) pView.findViewById(R.id.five);
five.setOnClickListener(this);
six = (Button) pView.findViewById(R.id.six);
six.setOnClickListener(this);
seven = (Button) pView.findViewById(R.id.seven);
seven.setOnClickListener(this);
eight = (Button) pView.findViewById(R.id.eight);
eight.setOnClickListener(this);
nine = (Button) pView.findViewById(R.id.nine);
nine.setOnClickListener(this);
blank = (Button) pView.findViewById(R.id.blank_Selection);
blank.setOnClickListener(this);
eraser = (ImageButton) pView.findViewById(R.id.eraser);
eraser.setOnClickListener(this);
}
public void showAtLocation(View v) {
pop.showAtLocation(v, Gravity.BOTTOM | Gravity.LEFT, 40, 40);
pView.startAnimation(appear);
}
public void dismiss(){
pop.dismiss();
}
public boolean isShowing() {
if(pop.isShowing()){
return true;
}else{
return false;
}
}
public int getSelected(){
return selected;
}
public void onClick(View arg0) {
if(arg0 == one){
Sudo.setToggleNum(1);
}else if(arg0 == two){
Sudo.setToggleNum(2);
}else if(arg0 == three){
Sudo.setToggleNum(3);
}else if(arg0 == four){
Sudo.setToggleNum(4);
}else if(arg0 == five){
Sudo.setToggleNum(5);
}else if(arg0 == six){
Sudo.setToggleNum(6);
}else if(arg0 == seven){
Sudo.setToggleNum(7);
}else if(arg0 == eight){
Sudo.setToggleNum(8);
}else if(arg0 == nine){
Sudo.setToggleNum(9);
}else if(arg0 == blank){
Sudo.setToggleNum(0);
}else if(arg0 == eraser){
Sudo.setToggleNum(-1);
}
this.dismiss();
}
}
The only effective way I've found to wipe out the PHP_AUTH_DIGEST
or PHP_AUTH_USER
AND PHP_AUTH_PW
credentials is to call the header HTTP/1.1 401 Unauthorized
.
function clear_admin_access(){
header('HTTP/1.1 401 Unauthorized');
die('Admin access turned off');
}
There're two kind of Django "projects" that I have in my ~/projects/
directory, both have a bit different structure.:
Mostly private projects, but doesn't have to be. It usually looks like this:
~/projects/project_name/
docs/ # documentation
scripts/
manage.py # installed to PATH via setup.py
project_name/ # project dir (the one which django-admin.py creates)
apps/ # project-specific applications
accounts/ # most frequent app, with custom user model
__init__.py
...
settings/ # settings for different environments, see below
__init__.py
production.py
development.py
...
__init__.py # contains project version
urls.py
wsgi.py
static/ # site-specific static files
templates/ # site-specific templates
tests/ # site-specific tests (mostly in-browser ones)
tmp/ # excluded from git
setup.py
requirements.txt
requirements_dev.txt
pytest.ini
...
The main settings are production ones. Other files (eg. staging.py
,
development.py
) simply import everything from production.py
and override only necessary variables.
For each environment, there are separate settings files, eg. production, development. I some projects I have also testing (for test runner), staging (as a check before final deploy) and heroku (for deploying to heroku) settings.
I rather specify requirements in setup.py directly. Only those required for
development/test environment I have in requirements_dev.txt
.
Some services (eg. heroku) requires to have requirements.txt
in root directory.
setup.py
Useful when deploying project using setuptools
. It adds manage.py
to PATH
, so I can run manage.py
directly (anywhere).
I used to put these apps into project_name/apps/
directory and import them
using relative imports.
I put these templates and static files into global templates/static directory, not inside each app. These files are usually edited by people, who doesn't care about project code structure or python at all. If you are full-stack developer working alone or in a small team, you can create per-app templates/static directory. It's really just a matter of taste.
The same applies for locale, although sometimes it's convenient to create separate locale directory.
Tests are usually better to place inside each app, but usually there is many integration/functional tests which tests more apps working together, so global tests directory does make sense.
There is temporary directory in project root, excluded from VCS. It's used to store media/static files and sqlite database during development. Everything in tmp could be deleted anytime without any problems.
I prefer virtualenvwrapper
and place all venvs into ~/.venvs
directory,
but you could place it inside tmp/
to keep it together.
I've created project template for this setup, django-start-template
Deployment of this project is following:
source $VENV/bin/activate
export DJANGO_SETTINGS_MODULE=project_name.settings.production
git pull
pip install -r requirements.txt
# Update database, static files, locales
manage.py syncdb --noinput
manage.py migrate
manage.py collectstatic --noinput
manage.py makemessages -a
manage.py compilemessages
# restart wsgi
touch project_name/wsgi.py
You can use rsync
instead of git
, but still you need to run batch of commands to update your environment.
Recently, I made django-deploy
app, which allows me to run single management command to update environment, but I've used it for one project only and I'm still experimenting with it.
Draft of templates I place inside global templates/
directory. I guess one can create folder sketches/
in project root, but haven't used it yet.
These apps are usually prepared to publish as open-source. I've taken example below from django-forme
~/projects/django-app/
docs/
app/
tests/
example_project/
LICENCE
MANIFEST.in
README.md
setup.py
pytest.ini
tox.ini
.travis.yml
...
Name of directories is clear (I hope). I put test files outside app directory,
but it really doesn't matter. It is important to provide README
and setup.py
, so package is easily installed through pip
.
You must use std namespace. If this code in main.cpp you should write
using namespace std;
If this declaration is in header, then you shouldn't include namespace and just write
std::string level;
This might help to understand what is recorded at what level Loggers may be assigned levels. Levels are instances of the log4net.Core.Level class. The following levels are defined in order of increasing severity - Log Level.
Number of levels recorded for each setting level:
ALL DEBUG INFO WARN ERROR FATAL OFF
•All
•DEBUG •DEBUG
•INFO •INFO •INFO
•WARN •WARN •WARN •WARN
•ERROR •ERROR •ERROR •ERROR •ERROR
•FATAL •FATAL •FATAL •FATAL •FATAL •FATAL
•OFF •OFF •OFF •OFF •OFF •OFF •OFF
try:
doSomething()
except Exception:
pass
else:
stuffDoneIf()
TryClauseSucceeds()
FYI the else clause can go after all exceptions and will only be run if the code in the try doesn't cause an exception.
Use CASE
:
SELECT
TABEL1.Id,
CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
THEN 'TRUE'
ELSE 'FALSE'
END AS NewFiled
FROM TABLE1
If TABLE2.ID
is Unique or a Primary Key, you could also use this:
SELECT
TABEL1.Id,
CASE WHEN TABLE2.ID IS NOT NULL
THEN 'TRUE'
ELSE 'FALSE'
END AS NewFiled
FROM TABLE1
LEFT JOIN Table2
ON TABLE2.ID = TABLE1.ID
MDN: https://developer.mozilla.org/en/DOM/window.location
It seems that you will get the same result for both, but hostname
contains clear host name without brackets or port number.
@Mahender, you probably meant the difference between \W
(instead of \w
) and \b
. If not, then I would agree with @BoltClock and @jwismar above. Otherwise continue reading.
\W
would match any non-word character and so its easy to try to use it to match word boundaries. The problem is that it will not match the start or end of a line. \b
is more suited for matching word boundaries as it will also match the start or end of a line. Roughly speaking (more experienced users can correct me here) \b
can be thought of as (\W|^|$)
. [Edit: as @?mega mentions below, \b
is a zero-length match so (\W|^|$)
is not strictly correct, but hopefully helps explain the diff]
Quick example: For the string Hello World
, .+\W
would match Hello_
(with the space) but will not match World
. .+\b
would match both Hello
and World
.
For Eclipse/STS v3.9.X windows user, you may need to update your subclipse version.
Go to Help > Install New Software > Click on Subclipse and edit the version from 1.6.X to 1.8.X
This method also apply to those who encounter JavaHL not available. You can check whether JavaHL is available or not by Go to Windows > Preference > Team > SVN. You may check it in SVN Interface > Client section.
If this work on MAC OS, kindly response in comment section. :)
This is a fairly comprehensive list from the Eclipse documentation. If anyone knows of another list — maybe with more details, or just the most common icons — feel free to add it.
Latest: JDT Icons
2019-06: JDT Icons
2019-03: JDT Icons
2018-12: JDT Icons
2018-09: JDT Icons
Photon: JDT Icons
Oxygen: JDT Icons
Neon: JDT Icons
Mars: JDT Icons
Luna: JDT Icons
Kepler: JDT Icons
Juno: JDT Icons
Indigo: JDT Icons
Helios: JDT Icons
There are also some CDT icons at the bottom of this help page.
If you're a Subversion user, the icons you're looking for may actually belong to Subclipse; see this excellent answer for more on those.
With an Android-powered device, you can develop and debug your Android applications just as you would on the emulator.
1. Declare your application as "debuggable" in AndroidManifest.xml
.
<application
android:debuggable="true"
... >
...
</application>
2. On your handset, navigate to Settings > Security and check Unknown sources
3. Go to Settings > Developer Options and check USB debugging
Note that if Developer Options
is invisible you will need to navigate to Settings > About Phone and tap on Build number
several times until you are notified that it has been unlocked.
4. Set up your system to detect your device.
Follow the instructions below for your OS:
Install the Google USB Driver from the ADT SDK Manager
(Support for: ADP1, ADP2, Verizon Droid, Nexus One, Nexus S).
For devices not listed above, install an OEM driver for your device
Your device should automatically work; Go to the next step
Add a udev
rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, click here. To set up device detection on Ubuntu Linux:
/etc/udev/rules.d/51-android.rules
.SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"
chmod a+r /etc/udev/rules.d/51-android.rules
Note: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules.
5. Run the project with your connected device.
With Eclipse/ADT: run or debug your application as usual. You will be presented with a Device Chooser dialog that lists the available emulator(s) and connected device(s).
With ADB: issue commands with the -d flag to target your connected device.
Still need help? Click here for the full guide.
Try connecting to a vpn, if possible. That was the reason I was facing problem. Tip: if you're using an ec2 machine, try rebooting it. This worked for me the other day :)
One more jQuery solution
For a single stylesheet with id "css" try this:
$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
Wrap it in a function that has global scrope and you can use it from the Developer Console in Chrome or Firebug in Firefox:
var reloadCSS = function() {
$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
};
I solved this by using this way -
@RunWith(SpringRunner.class)
@EnableJpaRepositories(basePackages={"com.path.repositories"})
@EntityScan(basePackages={"com.model"})
@TestPropertySource("classpath:application.properties")
@ContextConfiguration(classes = {ApiTestConfig.class,SaveActionsServiceImpl.class})
public class SaveCriticalProcedureTest {
@Autowired
private SaveActionsService saveActionsService;
.......
.......
}
For Swift 5
Remove Cell
let indexPath = [NSIndexPath(row: yourArray-1, section: 0)]
yourArray.remove(at: buttonTag)
self.tableView.beginUpdates()
self.tableView.deleteRows(at: indexPath as [IndexPath] , with: .fade)
self.tableView.endUpdates()
self.tableView.reloadData()// Not mendatory, But In my case its requires
Add new cell
yourArray.append(4)
tableView.beginUpdates()
tableView.insertRows(at: [
(NSIndexPath(row: yourArray.count-1, section: 0) as IndexPath)], with: .automatic)
tableView.endUpdates()
I solved this by adding .to_json
and some heading information
@result = HTTParty.post(@urlstring_to_post.to_str,
:body => { :subject => 'This is the screen name',
:issue_type => 'Application Problem',
:status => 'Open',
:priority => 'Normal',
:description => 'This is the description for the problem'
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
The accepted answer works for me only for the first 30 characters. This works for me:
select convert(varchar(max), convert(varbinary(max),myBlobColumn)) FROM table_name
You can declare like this
CREATE PROCEDURE MyProcName
@Parameter1 INT = 1,
@Parameter2 VARCHAR (100) = 'StringValue',
@Parameter3 VARCHAR (100) = NULL
AS
/* check for the NULL / default value (indicating nothing was passed */
if (@Parameter3 IS NULL)
BEGIN
/* whatever code you desire for a missing parameter*/
INSERT INTO ........
END
/* and use it in the query as so*/
SELECT *
FROM Table
WHERE Column = @Parameter
You may use this
/^(?:(?:\+|0{0,2})91(\s*|[\-])?|[0]?)?([6789]\d{2}([ -]?)\d{3}([ -]?)\d{4})$/
Valid Entries:
6856438922
7856128945
8945562713
9998564723
+91-9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 9883443344
+91-785-612-8945
+91 999 856 4723
Invalid Entries:
WAQU9876567892
ABCD9876541212
0226-895623124
0924645236
0222-895612
098-8956124
022-2413184
Validate it at https://regex101.com/
I had a bit of trouble getting this to work as well. Using brouxhaha's answer got me 90% of the way to what I was looking for. But the padding adjust wouldn't allow me to put the text anywhere I wanted. Using top and left seemed to work better for my purposes.
.project-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
color: #fff;
top: 80%;
left: 20%;
}
git branch --contains <ref>
is the most obvious "porcelain" command to do this. If you want to do something similar with only "plumbing" commands:
COMMIT=$(git rev-parse <ref>) # expands hash if needed
for BRANCH in $(git for-each-ref --format "%(refname)" refs/heads); do
if $(git rev-list $BRANCH | fgrep -q $COMMIT); then
echo $BRANCH
fi
done
(crosspost from this SO answer)
You have to reset that file to the original state and commit it again using --amend
. This is done easiest using git checkout HEAD^
.
Prepare demo:
$ git init
$ date >file-a
$ date >file-b
$ git add .
$ git commit -m "Initial commit"
$ date >file-a
$ date >file-b
$ git commit -a -m "the change which should only be file-a"
State before:
$ git show --stat
commit 4aa38f84e04d40a1cb40a5207ccd1a3cb3a4a317 (HEAD -> master)
Date: Wed Feb 7 17:24:45 2018 +0100
the change which should only be file-a
file-a | 2 +-
file-b | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
Here it comes: restore the previous version
$ git checkout HEAD^ file-b
commit it:
$ git commit --amend file-b
[master 9ef8b8b] the change which should only be file-a
Date: Wed Feb 7 17:24:45 2018 +0100
1 file changed, 1 insertion(+), 1 deletion(-)
State after:
$ git show --stat
commit 9ef8b8bab224c4d117f515fc9537255941b75885 (HEAD -> master)
Date: Wed Feb 7 17:24:45 2018 +0100
the change which should only be file-a
file-a | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
Just finished understanding Peek and Keep and had same confusion initially. The confusion arises becauses TempData behaves differently under different condition. You can watch this video which explains the Keep and Peek with demonstration https://www.facebook.com/video.php?v=689393794478113
Tempdata helps to preserve values for a single request and CAN ALSO preserve values for the next request depending on 4 conditions”.
If we understand these 4 points you would see more clarity.Below is a diagram with all 4 conditions, read the third and fourth point which talks about Peek and Keep.
Condition 1 (Not read):- If you set a “TempData” inside your action and if you do not read it in your view then “TempData” will be persisted for the next request.
Condition 2 ( Normal Read) :- If you read the “TempData” normally like the below code it will not persist for the next request.
string str = TempData["MyData"];
Even if you are displaying it’s a normal read like the code below.
@TempData["MyData"];
Condition 3 (Read and Keep) :- If you read the “TempData” and call the “Keep” method it will be persisted.
@TempData["MyData"];
TempData.Keep("MyData");
Condition 4 ( Peek and Read) :- If you read “TempData” by using the “Peek” method it will persist for the next request.
string str = TempData.Peek("Td").ToString();
Reference :- http://www.codeproject.com/Articles/818493/MVC-Tempdata-Peek-and-Keep-confusion
select top {LIMIT HERE} * from (
select *, ROW_NUMBER() over (order by {ORDER FIELD}) as r_n_n
from {YOUR TABLES} where {OTHER OPTIONAL FILTERS}
) xx where r_n_n >={OFFSET HERE}
A note:
This solution will only work in SQL Server 2005 or above, since this was when ROW_NUMBER()
was implemented.
Inspired by Robert K's solution, this version does not strip HTML tags, and is just as secure.
var decode_entities = (function() {
// Remove HTML Entities
var element = document.createElement('div');
function decode_HTML_entities (str) {
if(str && typeof str === 'string') {
// Escape HTML before decoding for HTML Entities
str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';');
element.innerHTML = str;
if(element.innerText){
str = element.innerText;
element.innerText = '';
}else{
// Firefox support
str = element.textContent;
element.textContent = '';
}
}
return unescape(str);
}
return decode_HTML_entities;
})();
you can run something like this (paste the code bellow in a .bat, or if you want it to run interractively replace the %%
by %
:
for %%i in (c:\directory\*.xls) do ssconvert %%i %%i.xlsx
If you can run powershell it will be :
Get-ChildItem -Path c:\directory -filter *.xls | foreach {ssconvert $($_.FullName) $($_.baseName).xlsx }
For performance, it usually best to make the code as simple and clear as possible and this will often perform well (as the JIT will optimise this code best). In your case, the simplest examples are also likely to be the fastest.
I would do either
int cmp = a > b ? +1 : a < b ? -1 : 0;
or a longer version
int cmp;
if (a > b)
cmp = +1;
else if (a < b)
cmp = -1;
else
cmp = 0;
or
int cmp = Integer.compare(a, b); // in Java 7
int cmp = Double.compare(a, b); // before Java 7
It's best not to create an object if you don't need to.
Performance wise, the first is best.
If you know for sure that you won't get an overflow you can use
int cmp = a - b; // if you know there wont be an overflow.
you won't get faster than this.
Scripting languages are a subset of programming languages.
I think based on the documentation of the @Before
and @After
the right conclusion is to give the methods unique names. I use the following pattern in my tests:
public abstract class AbstractBaseTest {
@Before
public final void baseSetUp() { // or any other meaningful name
System.out.println("AbstractBaseTest.setUp");
}
@After
public final void baseTearDown() { // or any other meaningful name
System.out.println("AbstractBaseTest.tearDown");
}
}
and
public class Test extends AbstractBaseTest {
@Before
public void setUp() {
System.out.println("Test.setUp");
}
@After
public void tearDown() {
System.out.println("Test.tearDown");
}
@Test
public void test1() throws Exception {
System.out.println("test1");
}
@Test
public void test2() throws Exception {
System.out.println("test2");
}
}
give as a result
AbstractBaseTest.setUp
Test.setUp
test1
Test.tearDown
AbstractBaseTest.tearDown
AbstractBaseTest.setUp
Test.setUp
test2
Test.tearDown
AbstractBaseTest.tearDown
Advantage of this approach: Users of the AbstractBaseTest class cannot override the setUp/tearDown methods by accident. If they want to, they need to know the exact name and can do it.
(Minor) disadvantage of this approach: Users cannot see that there are things happening before or after their setUp/tearDown. They need to know that these things are provided by the abstract class. But I assume that's the reason why they use the abstract class
if(n==1 || n==0){
return n;
}else{
return fib(n-1) + fib(n-2);
}
However, using recursion to get fibonacci number is bad practice, because function is called about 8.5 times than received number. E.g. to get fibonacci number of 30 (1346269) - function is called 7049122 times!
To compatibility with both py2 and py3
import six
import base64
def b64encode(source):
if six.PY3:
source = source.encode('utf-8')
content = base64.b64encode(source).decode('utf-8')
Allain basically has the java code, so you can use that. However, his expression only matches if your numbers are only preceded by a stream of word characters.
"(\\d+)"
should be able to find the first string of digits. You don't need to specify what's before it, if you're sure that it's going to be the first string of digits. Likewise, there is no use to specify what's after it, unless you want that. If you just want the number, and are sure that it will be the first string of one or more digits then that's all you need.
If you expect it to be offset by spaces, it will make it even more distinct to specify
"\\s+(\\d+)\\s+"
might be better.
If you need all three parts, this will do:
"(\\D+)(\\d+)(.*)"
EDIT The Expressions given by Allain and Jack suggest that you need to specify some subset of non-digits in order to capture digits. If you tell the regex engine you're looking for \d
then it's going to ignore everything before the digits. If J or A's expression fits your pattern, then the whole match equals the input string. And there's no reason to specify it. It probably slows a clean match down, if it isn't totally ignored.
Could not get this to work until I put Authorization in single quotes:
axios.get(URL, { headers: { 'Authorization': AuthStr } })
The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.
If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.
I suggest Freewall
. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.
Home page and document: also found here
.
Note that Git 2.5 (Q2 2015) a future Git might try to make that scenario impossible.
See commit ed178ef by Jeff King (peff
), 22 Apr 2015.
(Merged by Junio C Hamano -- gitster
-- in commit 05c3967, 19 May 2015)
Note: This has been reverted. See below.
stash
: require a clean index to apply/pop
If you have staged contents in your index and run "
stash apply/pop
", we may hit a conflict and put new entries into the index.
Recovering to your original state is difficult at that point, because tools like "git reset --keep" will blow away anything staged.
In other words:
"
git stash pop/apply
" forgot to make sure that not just the working tree is clean but also the index is clean.
The latter is important as a stash application can conflict and the index will be used for conflict resolution.
We can make this safer by refusing to apply when there are staged changes.
That means if there were merges before because of applying a stash on modified files (added but not committed), now they would not be any merges because the stash apply/pop would stop immediately with:
Cannot apply stash: Your index contains uncommitted changes.
Forcing you to commit the changes means that, in case of merges, you can easily restore the initial state( before
git stash apply/pop
) with agit reset --hard
.
See commit 1937610 (15 Jun 2015), and commit ed178ef (22 Apr 2015) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit bfb539b, 24 Jun 2015)
That commit was an attempt to improve the safety of applying a stash, because the application process may create conflicted index entries, after which it is hard to restore the original index state.
Unfortunately, this hurts some common workflows around "
git stash -k
", like:
git add -p ;# (1) stage set of proposed changes
git stash -k ;# (2) get rid of everything else
make test ;# (3) make sure proposal is reasonable
git stash apply ;# (4) restore original working tree
If you "git commit" between steps (3) and (4), then this just works. However, if these steps are part of a pre-commit hook, you don't have that opportunity (you have to restore the original state regardless of whether the tests passed or failed).
SELECT *
FROM logs
WHERE pw='correct'
AND CASE
WHEN id<800 THEN success=1
ELSE 1=1
END
AND YEAR(TIMESTAMP)=2011
Very easy..
int (name of integer) = [(name of string, no ()) intValue];
It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:
if (Model.Model2 == null
|| Model.Model2.Model3 == null
|| Model.Model2.Model3.Model4 == null
|| Model.Model2.Model3.Model4.Name == null)
{
mapped.Name = "N/A"
}
else
{
mapped.Name = Model.Model2.Model3.Model4.Name;
}
It can be written like (same logic as above)
mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A";
DotNetFiddle.Net Working Example.
(the ?? or null-coalescing operator is different than the ? or null conditional operator).
It can also be used out side of assignment operators with Action. Instead of
Action<TValue> myAction = null;
if (myAction != null)
{
myAction(TValue);
}
It can be simplified to:
myAction?.Invoke(TValue);
using System;
public class Program
{
public static void Main()
{
Action<string> consoleWrite = null;
consoleWrite?.Invoke("Test 1");
consoleWrite = (s) => Console.WriteLine(s);
consoleWrite?.Invoke("Test 2");
}
}
Result:
Test 2
Yes, it's possible, the syntax is curl [protocol://]<host>[:port]
, for example:
curl example.com:1234
If you're using Bash, you can also use pseudo-device /dev
files to open a TCP connection, e.g.:
exec 5<>/dev/tcp/127.0.0.1/1234
echo "send some stuff" >&5
cat <&5 # Receive some stuff.
See also: More on Using Bash's Built-in /dev/tcp File (TCP/IP).
I was also confused by this, and below is what I have learned.
When you clone a repository, for example from GitHub:
origin
is the alias for the URL from which you cloned the repository. Note that you can change this alias.
There is one master
branch in the remote repository (aliased by origin
). There is also another master
branch created locally.
Further information can be found from this SO question: Git branching: master vs. origin/master vs. remotes/origin/master
can you remove them in a nightly process, storing them in a separate field, then do an update on changed records right before you run the process?
Or on the insert/update, store the "numeric" format, to reference later. A trigger would be an easy way to do it.
The event when user releases his finger is MotionEvent.ACTION_UP
. I'm not aware if there are any guidelines which prohibit using View.OnTouchListener instead of onClick(), most probably it depends of situation.
Here's a sample code:
imageButton.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
// Do what you want
return true;
}
return false;
}
});
Shouldn't you have:
DELETE FROM tableA WHERE entitynum IN (...your select...)
Now you just have a WHERE with no comparison:
DELETE FROM tableA WHERE (...your select...)
So your final query would look like this;
DELETE FROM tableA WHERE entitynum IN (
SELECT tableA.entitynum FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date')
)
We finally found an answer of sorts. First, the problem: the table always sizes itself around the content, rather than forcing the content to fit in the table. That limits your options.
We did it by setting the content div to display:none, letting the table size itself, and then in javascript setting the height and width of the content div to the inner height and width of the enclosing td tag. Show the content div. Repeat the process when the window is resized.
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
An array "decays" into a pointer to its first element, so scanf("%s", string)
is equivalent to scanf("%s", &string[0])
. On the other hand, scanf("%s", &string)
passes a pointer-to-char[256]
, but it points to the same place.
Then scanf
, when processing the tail of its argument list, will try to pull out a char *
. That's the Right Thing when you've passed in string
or &string[0]
, but when you've passed in &string
you're depending on something that the language standard doesn't guarantee, namely that the pointers &string
and &string[0]
-- pointers to objects of different types and sizes that start at the same place -- are represented the same way.
I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)
To set fixed 2 digits after the decimal point use these first:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
Then print your double values.
This is an example:
#include <iostream>
using std::cout;
using std::ios;
using std::endl;
int main(int argc, char *argv[]) {
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
double d = 10.90;
cout << d << endl;
return 0;
}
Add a column for example 'Selected' First. Then Filter your data. Go to the column 'Selected'. Provide any proxy text or number to all rows. like '1' or 'A' - now your hidden Rows are Blank Now, Clear Filter and Use Sorting - two levels Sort by - 'Selected' Ascending - this leaves blank cells at bottom Add Sort Level - 'Any column you Desire' your order
Now, Why dont you drag the autofill yourself.
Oops, I have no reputation here.
The message means that both the packages have functions with the same names. In this particular case, the testthat
and assertive
packages contain five functions with the same name.
R will look through the search
path to find functions, and will use the first one that it finds.
search()
## [1] ".GlobalEnv" "package:assertive" "package:testthat"
## [4] "tools:rstudio" "package:stats" "package:graphics"
## [7] "package:grDevices" "package:utils" "package:datasets"
## [10] "package:methods" "Autoloads" "package:base"
In this case, since assertive
was loaded after testthat
, it appears earlier in the search path, so the functions in that package will be used.
is_true
## function (x, .xname = get_name_in_parent(x))
## {
## x <- coerce_to(x, "logical", .xname)
## call_and_name(function(x) {
## ok <- x & !is.na(x)
## set_cause(ok, ifelse(is.na(x), "missing", "false"))
## }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>
The functions in testthat
are not accessible in the usual way; that is, they have been masked.
You can explicitly provide a package name when you call a function, using the double colon operator, ::
. For example:
testthat::is_true
## function ()
## {
## function(x) expect_true(x)
## }
## <environment: namespace:testthat>
If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE
to library
.
library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time
Alternatively, suppress the message with suppressPackageStartupMessages
:
library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output
If you have altered some of R's startup configuration options (see ?Startup
) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup
should solve most mysteries.
For example, the documentation there says:
Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.
Which implies that when 3rd party packages are loaded via files like .Rprofile
you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.
First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.
library(dplyr)
envs <- search() %>% setNames(., .)
For each environment, get the exported functions (and other variables).
fns <- lapply(envs, ls)
Turn this into a data frame, for easy use with dplyr.
fns_by_env <- data_frame(
env = rep.int(names(fns), lengths(fns)),
fn = unlist(fns)
)
Find cases where the object appears more than once.
fns_by_env %>%
group_by(fn) %>%
tally() %>%
filter(n > 1) %>%
inner_join(fns_by_env)
To test this, try loading some packages with known conflicts (e.g., Hmisc
, AnnotationDbi
).
The conflicted
package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.
library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
## * Hmisc::units
## * base::units
I had the same error in Laravel 5.2, turns out the namespace is incorrect in the model class definition.
I created my model using the command:
php artisan make:model myModel
By default, Laravel 5 creates the model under App
folder, but if you were to move the model to another folder like I did, you must change the the namespace inside the model definition too:
namespace App\ModelFolder;
To include the folder name when creating the model you could use (don't forget to use double back slashes):
php artisan make:model ModelFolder\\myModel
Did you ever hated to write such variable initializers?
XmlSerializer xmlSerializer = new XmlSerialzer(typeof(int))
So, starting with C# 3.0, you can replace it with
var xmlSerializer = new XmlSerialzer(typeof(int))
One notice: Type is resolved during compilation, so no problems with performance. But Compiler should be able to detect type during build step, so code like var xmlSerializer;
won't compile at all.
SELECT productid FROM product WHERE purchase_date > sysdate-30
Attribute is a synonym of field
for array.length
This is now possible as of TFS 2015 by using the Code Search
plugin. https://marketplace.visualstudio.com/items?itemName=ms.vss-code-search
The search is done via the web interface, and does not require you to download the code to your local machine which is nice.
Add a ::after
which autofills the space. No need to pollute your HTML. Here is a codepen showing it: http://codepen.io/DanAndreasson/pen/ZQXLXj
.grid {
display: flex;
flex-flow: row wrap;
justify-content: space-between;
}
.grid::after {
content: "";
flex: auto;
}
To be convert the image to byte array.The code is give below.
public byte[] ImageToByteArray(System.Drawing.Image images)
{
using (var _memorystream = new MemoryStream())
{
images.Save(_memorystream ,images.RawFormat);
return _memorystream .ToArray();
}
}
To be convert the Byte array to Image.The code is given below.The code is handle A Generic error occurred in GDI+
in Image Save.
public void SaveImage(string base64String, string filepath)
{
// image convert to base64string is base64String
//File path is which path to save the image.
var bytess = Convert.FromBase64String(base64String);
using (var imageFile = new FileStream(filepath, FileMode.Create))
{
imageFile.Write(bytess, 0, bytess.Length);
imageFile.Flush();
}
}
First give your form an id
attribute, then use code like this:
$(document).ready( function() {
var form = $('#my_awesome_form');
form.find('select:first').change( function() {
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
console.log( response );
}
} );
} );
} );
So this code uses .serialize()
to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.
For future reference, the jQuery docs are very, very good.
It's because, even in "raw" strings (=strings with an r
before the starting quote(s)), an unescaped escape character cannot be the last character in the string. This should work instead:
'\\ '[0]
No one has mentioned the obvious:
var myCallback = function() { console.log("name or age changed"); };
$scope.$watch("name", myCallback);
$scope.$watch("age", myCallback);
This might mean a little less polling. If you watch both name + age
(for this) and name
(elsewhere) then I assume Angular will effectively look at name
twice to see if it's dirty.
It's arguably more readable to use the callback by name instead of inlining it. Especially if you can give it a better name than in my example.
And you can watch the values in different ways if you need to:
$scope.$watch("buyers", myCallback, true);
$scope.$watchCollection("sellers", myCallback);
$watchGroup
is nice if you can use it, but as far as I can tell, it doesn't let you watch the group members as a collection or with object equality.
If you need the old and new values of both expressions inside one and the same callback function call, then perhaps some of the other proposed solutions are more convenient.
Very few people realize the power of css positioning. To set the map to occupy 100% height of it's parent container do following:
#map_canvas_container {position: relative;}
#map_canvas {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}
If you have any non absolutely positioned elements inside #map_canvas_container they will set the height of it and the map will take the exact available space.
I am posting my answer because I suspect there might be someone out there for whom the above solutions might not have worked.
So, you are getting a warning,
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server: (project name)' did not find a matching property.
Rather than disabling this warning by checking that option in Server configuration (I did try that) I would suggest you do this:
Now if you successfully found that there is a bug in your app, the probable place would be look for a web.xml file which the container uses for loading the app. In my case I had misspelled a name in servlet mapping which made me debug meaninglessly for 3 hours. Your problem might be someplace else.
And another thing, if you have many apps synchronized with the server,there is a possibility some other app's context might be the source of problem. Try debugging one by one.
With argc
(argument count) and argv
(argument vector) you can get the number and the values of passed arguments when your application has been launched.
This way you can use parameters (such as -version
) when your application is started to act a different way.
But you can also use int main(void)
as a prototype in C.
There is a third (less known and nonstandard) prototype with a third argument which is envp
. It contains environment variables.
Resources:
While @jackofallcode answer is correct, it can be written in one line:
((RelativeLayout.LayoutParams) viewToLayout.getLayoutParams()).addRule(RelativeLayout.BELOW, R.id.below_id);
In R, you can assign your own operators using %[characters]%
. A trivial example:
'%p%' <- function(x, y){x^2 + y}
2 %p% 3 # result: 7
While I agree with BlueTrin that %%
is pretty standard, I have a suspicion %/%
may have something to do with the sort of operator definitions I showed above - perhaps it was easier to implement, and makes sense: %/%
means do a special sort of division (integer division)
I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.
One can write his own customised ufunc
in C, which surely is more efficient, or by invoking np.frompyfunc
, which is built-in factory method. After testing, this is more efficient than np.vectorize
:
f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)
%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms
I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post
You can also make additions to this path with the PYTHONPATH environment variable at runtime, in addition to:
import sys
sys.path.append('/home/user/python-libs')
public static void main(String[] args) throws IOException {
String filePath = "/Users/myXml/VH181.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
printElement(doc);
System.out.println("XML file updated successfully");
} catch (SAXException | ParserConfigurationException e1) {
e1.printStackTrace();
}
}
private static void printElement(Document someNode) {
NodeList nodeList = someNode.getElementsByTagName("choiceInteraction");
for(int z=0,size= nodeList.getLength();z<size; z++) {
String Value = nodeList.item(z).getAttributes().getNamedItem("id").getNodeValue();
System.out.println("Choice Interaction Id:"+Value);
}
}
we Can try this code using method
Make sure that you have valid cacerts in the JRE/security, otherwise you will not bypass the invalid empty trustAnchors error.
In my Amazon EC2 Opensuse12 installation, the problem was that the file pointed by the cacerts in the JRE security directory was invalid:
$ java -version
java version "1.7.0_09"
OpenJDK Runtime Environment (IcedTea7 2.3.4) (suse-3.20.1-x86_64)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)
$ ls -l /var/lib/ca-certificates/
-rw-r--r-- 1 root 363 Feb 28 14:17 ca-bundle.pem
$ ls -l /usr/lib64/jvm/jre/lib/security/
lrwxrwxrwx 1 root 37 Mar 21 00:16 cacerts -> /var/lib/ca-certificates/java-cacerts
-rw-r--r-- 1 root 2254 Jan 18 16:50 java.policy
-rw-r--r-- 1 root 15374 Jan 18 16:50 java.security
-rw-r--r-- 1 root 88 Jan 18 17:34 nss.cfg
So I solved installing an old Opensuse 11 valid certificates. (sorry about that!!)
$ ll
total 616
-rw-r--r-- 1 root 220065 Jan 31 15:48 ca-bundle.pem
-rw-r--r-- 1 root 363 Feb 28 14:17 ca-bundle.pem.old
-rw-r--r-- 1 root 161555 Jan 31 15:48 java-cacerts
I understood that you could use the keytool to generate a new one (http://mail.openjdk.java.net/pipermail/distro-pkg-dev/2010-April/008961.html). I'll probably have to that soon.
regards lellis
Go to this link here https://drive.google.com/file/d/0B9mUXEcOsbhfdFR1ZnVKNWtXQlU/view Cuodos To https://www.reddit.com/r/iOSProgramming/comments/6fmtj1/is_it_possible_to_download_xcode_9_beta_without_a/dikyeh4/
This is equivalent to the path of the script:
%~dp0
This uses the batch parameter extension syntax. Parameter 0 is always the script itself.
If your script is stored at C:\example\script.bat
, then %~dp0
evaluates to C:\example\
.
ss64.com has more information about the parameter extension syntax. Here is the relevant excerpt:
You can get the value of any parameter using a % followed by it's numerical position on the command line.
[...]
When a parameter is used to supply a filename then the following extended syntax can be applied:
[...]
%~d1 Expand %1 to a Drive letter only - C:
[...]
%~p1 Expand %1 to a Path only e.g. \utils\ this includes a trailing \ which may be interpreted as an escape character by some commands.
[...]
The modifiers above can be combined:
%~dp1 Expand %1 to a drive letter and path only
[...]
You can get the pathname of the batch script itself with %0, parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script e.g. W:\scripts\
Here is a solution witch takes into account duplicate entries. It is written in javascript and assumes array is sorted. The solution runs in O(n) time and does not use any extra memory aside from variable.
var count_pairs = function(_arr,x) {
if(!x) x = 0;
var pairs = 0;
var i = 0;
var k = _arr.length-1;
if((k+1)<2) return pairs;
var halfX = x/2;
while(i<k) {
var curK = _arr[k];
var curI = _arr[i];
var pairsThisLoop = 0;
if(curK+curI==x) {
// if midpoint and equal find combinations
if(curK==curI) {
var comb = 1;
while(--k>=i) pairs+=(comb++);
break;
}
// count pair and k duplicates
pairsThisLoop++;
while(_arr[--k]==curK) pairsThisLoop++;
// add k side pairs to running total for every i side pair found
pairs+=pairsThisLoop;
while(_arr[++i]==curI) pairs+=pairsThisLoop;
} else {
// if we are at a mid point
if(curK==curI) break;
var distK = Math.abs(halfX-curK);
var distI = Math.abs(halfX-curI);
if(distI > distK) while(_arr[++i]==curI);
else while(_arr[--k]==curK);
}
}
return pairs;
}
I solved this during an interview for a large corporation. They took it but not me. So here it is for everyone.
Start at both side of the array and slowly work your way inwards making sure to count duplicates if they exist.
It only counts pairs but can be reworked to
Enjoy!
You can increase the limit from php.ini file. If you are using windows, you will the get php.ini file from C:\xampp\php directory.
Now changes the following lines & set your limit
post_max_size = 128M
upload_max_filesize = 128M
max_execution_time = 2000
max_input_time = 3000
memory_limit = 256M
Well as we all know that it gets erased. But it can be known under some circumstances where the type is explicitly mentioned in the class hierarchy:
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public abstract class CaptureType<T> {
/**
* {@link java.lang.reflect.Type} object of the corresponding generic type. This method is useful to obtain every kind of information (including annotations) of the generic type.
*
* @return Type object. null if type could not be obtained (This happens in case of generic type whose information cant be obtained using Reflection). Please refer documentation of {@link com.types.CaptureType}
*/
public Type getTypeParam() {
Class<?> bottom = getClass();
Map<TypeVariable<?>, Type> reifyMap = new LinkedHashMap<>();
for (; ; ) {
Type genericSuper = bottom.getGenericSuperclass();
if (!(genericSuper instanceof Class)) {
ParameterizedType generic = (ParameterizedType) genericSuper;
Class<?> actualClaz = (Class<?>) generic.getRawType();
TypeVariable<? extends Class<?>>[] typeParameters = actualClaz.getTypeParameters();
Type[] reified = generic.getActualTypeArguments();
assert (typeParameters.length != 0);
for (int i = 0; i < typeParameters.length; i++) {
reifyMap.put(typeParameters[i], reified[i]);
}
}
if (bottom.getSuperclass().equals(CaptureType.class)) {
bottom = bottom.getSuperclass();
break;
}
bottom = bottom.getSuperclass();
}
TypeVariable<?> var = bottom.getTypeParameters()[0];
while (true) {
Type type = reifyMap.get(var);
if (type instanceof TypeVariable) {
var = (TypeVariable<?>) type;
} else {
return type;
}
}
}
/**
* Returns the raw type of the generic type.
* <p>For example in case of {@code CaptureType<String>}, it would return {@code Class<String>}</p>
* For more comprehensive examples, go through javadocs of {@link com.types.CaptureType}
*
* @return Class object
* @throws java.lang.RuntimeException If the type information cant be obtained. Refer documentation of {@link com.types.CaptureType}
* @see com.types.CaptureType
*/
public Class<T> getRawType() {
Type typeParam = getTypeParam();
if (typeParam != null)
return getClass(typeParam);
else throw new RuntimeException("Could not obtain type information");
}
/**
* Gets the {@link java.lang.Class} object of the argument type.
* <p>If the type is an {@link java.lang.reflect.ParameterizedType}, then it returns its {@link java.lang.reflect.ParameterizedType#getRawType()}</p>
*
* @param type The type
* @param <A> type of class object expected
* @return The Class<A> object of the type
* @throws java.lang.RuntimeException If the type is a {@link java.lang.reflect.TypeVariable}. In such cases, it is impossible to obtain the Class object
*/
public static <A> Class<A> getClass(Type type) {
if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
Class<?> componentClass = getClass(componentType);
if (componentClass != null) {
return (Class<A>) Array.newInstance(componentClass, 0).getClass();
} else throw new UnsupportedOperationException("Unknown class: " + type.getClass());
} else if (type instanceof Class) {
Class claz = (Class) type;
return claz;
} else if (type instanceof ParameterizedType) {
return getClass(((ParameterizedType) type).getRawType());
} else if (type instanceof TypeVariable) {
throw new RuntimeException("The type signature is erased. The type class cant be known by using reflection");
} else throw new UnsupportedOperationException("Unknown class: " + type.getClass());
}
/**
* This method is the preferred method of usage in case of complex generic types.
* <p>It returns {@link com.types.TypeADT} object which contains nested information of the type parameters</p>
*
* @return TypeADT object
* @throws java.lang.RuntimeException If the type information cant be obtained. Refer documentation of {@link com.types.CaptureType}
*/
public TypeADT getParamADT() {
return recursiveADT(getTypeParam());
}
private TypeADT recursiveADT(Type type) {
if (type instanceof Class) {
return new TypeADT((Class<?>) type, null);
} else if (type instanceof ParameterizedType) {
ArrayList<TypeADT> generic = new ArrayList<>();
ParameterizedType type1 = (ParameterizedType) type;
return new TypeADT((Class<?>) type1.getRawType(),
Arrays.stream(type1.getActualTypeArguments()).map(x -> recursiveADT(x)).collect(Collectors.toList()));
} else throw new UnsupportedOperationException();
}
}
public class TypeADT {
private final Class<?> reify;
private final List<TypeADT> parametrized;
TypeADT(Class<?> reify, List<TypeADT> parametrized) {
this.reify = reify;
this.parametrized = parametrized;
}
public Class<?> getRawType() {
return reify;
}
public List<TypeADT> getParameters() {
return parametrized;
}
}
And now you can do things like:
static void test1() {
CaptureType<String> t1 = new CaptureType<String>() {
};
equals(t1.getRawType(), String.class);
}
static void test2() {
CaptureType<List<String>> t1 = new CaptureType<List<String>>() {
};
equals(t1.getRawType(), List.class);
equals(t1.getParamADT().getParameters().get(0).getRawType(), String.class);
}
private static void test3() {
CaptureType<List<List<String>>> t1 = new CaptureType<List<List<String>>>() {
};
equals(t1.getParamADT().getRawType(), List.class);
equals(t1.getParamADT().getParameters().get(0).getRawType(), List.class);
}
static class Test4 extends CaptureType<List<String>> {
}
static void test4() {
Test4 test4 = new Test4();
equals(test4.getParamADT().getRawType(), List.class);
}
static class PreTest5<S> extends CaptureType<Integer> {
}
static class Test5 extends PreTest5<Integer> {
}
static void test5() {
Test5 test5 = new Test5();
equals(test5.getTypeParam(), Integer.class);
}
static class PreTest6<S> extends CaptureType<S> {
}
static class Test6 extends PreTest6<Integer> {
}
static void test6() {
Test6 test6 = new Test6();
equals(test6.getTypeParam(), Integer.class);
}
class X<T> extends CaptureType<T> {
}
class Y<A, B> extends X<B> {
}
class Z<Q> extends Y<Q, Map<Integer, List<List<List<Integer>>>>> {
}
void test7(){
Z<String> z = new Z<>();
TypeADT param = z.getParamADT();
equals(param.getRawType(), Map.class);
List<TypeADT> parameters = param.getParameters();
equals(parameters.get(0).getRawType(), Integer.class);
equals(parameters.get(1).getRawType(), List.class);
equals(parameters.get(1).getParameters().get(0).getRawType(), List.class);
equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getRawType(), List.class);
equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getParameters().get(0).getRawType(), Integer.class);
}
static void test8() throws IllegalAccessException, InstantiationException {
CaptureType<int[]> type = new CaptureType<int[]>() {
};
equals(type.getRawType(), int[].class);
}
static void test9(){
CaptureType<String[]> type = new CaptureType<String[]>() {
};
equals(type.getRawType(), String[].class);
}
static class SomeClass<T> extends CaptureType<T>{}
static void test10(){
SomeClass<String> claz = new SomeClass<>();
try{
claz.getRawType();
throw new RuntimeException("Shouldnt come here");
}catch (RuntimeException ex){
}
}
static void equals(Object a, Object b) {
if (!a.equals(b)) {
throw new RuntimeException("Test failed. " + a + " != " + b);
}
}
More info here. But again, it is almost impossible to retrieve for:
class SomeClass<T> extends CaptureType<T>{}
SomeClass<String> claz = new SomeClass<>();
where it gets erased.
zip()
in conjunction with the *
operator can be used to unzip
a list
unzip_lst = zip(*mylist)
for i in unzip_lst:
for j in i:
print j
If you strictly want to stick to using button,Then simply create an open window function as follows:
<script>
function myfunction() {
window.open("mynewpage.html");
}
</script>
Then in your html do the following with your button:
Join
So you would have something like this:
<body>
<script>
function joinfunction() {
window.open("mynewpage.html");
}
</script>
<button onclick="myfunction()" type="button" class="btn btn-default subs-btn">Join</button>
Following link may help you http://angrytools.com/gradient/ .This will create custom gradient background in android as like in photoshop.
Have you tried:
SELECT Cast( 2.555 as decimal(53,8))
This would return 2.55500000
. Is that what you want?
UPDATE:
Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:
SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')
returns 8|7
You may be able to use this in your conversion process...
<head>
<script type="text/javascript">
function SetMaxLength () {
var input = document.getElementById ("myInput");
input.maxLength = 10;
}
</script>
</head>
<body>
<input id="myInput" type="text" size="20" />
</body>
Concatenate the attribute selectors:
input[name="Sex"][value="M"]
If aim is to create a resources folder parallel to src/main/java, then do the following:
Right Click on your project > New > Source Folder
Provide Folder Name as src/main/resources
Finish
For Googlers:
STATEFULNESS
MECHANISMS
Authorization
, are just headers without any special treatment, client has to manage all aspects of the transferSTATEFULNESS COMPARISON
hash(data + secret key)
, where secret key is only known to server, so the integrity of token data can be verifiedMECHANISM COMPARISON
httpOnly
thus prevent client JavaScript accessSUM-UP
I have to read own parameters by startup.
That has to be there before the WebHost is started (as I need the “to listen” url/IP and port from the parameter file and apply it to the WebHost). Further, I need the settings public in the whole application.
After searching for a while (no complete example found, only snippets) and after various try-and-error's, I have decided to do it the “old way" with an own .ini file.
So.. if you want to use your own .ini file and/or set the "to listen url/IP" your own and/or need the settings public, this is for you...
Complete example, valid for core 2.1 (mvc):
Create an .ini-file - example:
[Startup]
URL=http://172.16.1.201:22222
[Parameter]
*Dummy1=gew7623
Dummy1=true
Dummy2=1
whereby the Dummyx are only included as example for other date types than string (and also to test the case “wrong param” (see code below).
Added a code file in the root of the project, to store the global variables:
namespace MatrixGuide
{
public static class GV
{
// In this class all gobals are defined
static string _cURL;
public static string cURL // URL (IP + Port) on that the application has to listen
{
get { return _cURL; }
set { _cURL = value; }
}
static bool _bdummy1;
public static bool bdummy1 //
{
get { return _bdummy1; }
set { _bdummy1 = value; }
}
static int _idummy1;
public static int idummy1 //
{
get { return _idummy1; }
set { _idummy1 = value; }
}
static bool _bFehler_Ini;
public static bool bFehler_Ini //
{
get { return _bFehler_Ini; }
set { _bFehler_Ini = value; }
}
// add further GV variables here..
}
// Add further classes here...
}
Changed the code in program.cs (before CreateWebHostBuilder()):
namespace MatrixGuide
{
public class Program
{
public static void Main(string[] args)
{
// Read .ini file and overtake the contend in globale
// Do it in an try-catch to be able to react to errors
GV.bFehler_Ini = false;
try
{
var iniconfig = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddIniFile("matrixGuide.ini", optional: false, reloadOnChange: true)
.Build();
string cURL = iniconfig.GetValue<string>("Startup:URL");
bool bdummy1 = iniconfig.GetValue<bool>("Parameter:Dummy1");
int idummy2 = iniconfig.GetValue<int>("Parameter:Dummy2");
//
GV.cURL = cURL;
GV.bdummy1 = bdummy1;
GV.idummy1 = idummy2;
}
catch (Exception e)
{
GV.bFehler_Ini = true;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("!! Fehler beim Lesen von MatrixGuide.ini !!");
Console.WriteLine("Message:" + e.Message);
if (!(e.InnerException != null))
{
Console.WriteLine("InnerException: " + e.InnerException.ToString());
}
Console.ForegroundColor = ConsoleColor.White;
}
// End .ini file processing
//
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>() //;
.UseUrls(GV.cURL, "http://localhost:5000"); // set the to use URL from .ini -> no impact to IISExpress
}
}
This way:
Use List.AddRange(collection As IEnumerable(Of T)) method.
It allows you to append at the end of your list another collection/list.
Example:
List<string> initialList = new List<string>();
// Put whatever you want in the initial list
List<string> listToAdd = new List<string>();
// Put whatever you want in the second list
initialList.AddRange(listToAdd);
I think that most of the time when people ask this question, they have build a site with only divs, and now one of the div needs to be a link.
I seen someone use a transparent empty image, PNG, inside an anchor tag just to make a link inside a div, and the image was the same size as the div.
Pretty sad actually...but it works...
After much aggravation, I discovered how to scroll in iframes on my ipad. The secret was to do a vertical finger swipe (single finger was fine) on the LEFT side of the iframe area (and maybe slightly outside of the border). On a laptop or PC, the scroll bar is on the right, so naturally, I spent of lot of time on my ipad experimenting with finger motions on the right side. Only when I tried the left side would the iframe scroll.
For the sake of completion: if you want to convert fixed point representation to its binary equivalent you can perform the following operations:
Get the integer and fractional part.
from decimal import *
a = Decimal(3.625)
a_split = (int(a//1),a%1)
Convert the fractional part in its binary representation. To achieve this multiply successively by 2.
fr = a_split[1]
str(int(fr*2)) + str(int(2*(fr*2)%1)) + ...
You can read the explanation here.
It's because there is no long
in javascript.
If you want to just compare dates,
yourdatetime.date() < datetime.today().date()
Or, obviously,
yourdatetime.date() == datetime.today().date()
If you want to check that they're the same date.
The documentation is usually helpful. It is also usually the first google result for python thing_i_have_a_question_about
. Unless your question is about a function/module named "snake".
Basically, the datetime
module has three types for storing a point in time:
date
for year, month, day of monthtime
for hours, minutes, seconds, microseconds, time zone infodatetime
combines date and time. It has the methods date()
and time()
to get the corresponding date
and time
objects, and there's a handy combine
function to combine date
and time
into a datetime
.I have gone through similar error. The error was not coming earlier, but recently I reinstall my oracle db and change the instance name from 'xe' to 'orcl', but forget to change this piece of code in property file:
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:***xe***
spring.datasource.username=system
spring.datasource.password=manager
Once I change it from 'xe' to 'orcl' everything is fine.
In perl
perl -ane '{ if(m/[[:^ascii:]]/) { print } }' fileName > newFile
You need to do the following:
Create a background with rounded corners for the Dialog's background:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#fff" />
<corners
android:bottomLeftRadius="8dp"
android:bottomRightRadius="8dp"
android:topLeftRadius="8dp"
android:topRightRadius="8dp" />
</shape>
Now in your Dialog's XML file in the root layout use that background with required margin:
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:background="@drawable/dialog_background"
finally in the java part you need to do this:
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(layoutResId);
View v = getWindow().getDecorView();
v.setBackgroundResource(android.R.color.transparent);
This works perfectly for me.
One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.
I am just going to show as a static example which you can accommodate in your real world.
On each of your <tr>
's add a data attribute for id
(i.e. data-id
) with the corresponding id value and specify a data-target
, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal
to make this a trigger for modal.
<tr data-toggle="modal" data-id="1" data-target="#orderModal">
<td>1</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-toggle="modal" data-id="2" data-target="#orderModal">
<td>2</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-toggle="modal" data-id="3" data-target="#orderModal">
<td>3</td>
<td>24234234</td>
<td>A</td>
</tr>
And now in the javascript just set up the modal just once and event listen to its events so you can do your work.
$(function(){
$('#orderModal').modal({
keyboard: true,
backdrop: "static",
show:false,
}).on('show', function(){ //subscribe to show method
var getIdFromRow = $(event.target).closest('tr').data('id'); //get the id from tr
//make your ajax call populate items or what even you need
$(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow + '</b>'))
});
});
Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.
Alternative ways here:
I have modified the above solutions and replaced Files.walk
with Files.list
. This also assumes the directory you are zipping only contains file and not any sub directories.
private void zipDirectory(Path dirPath) throws IOException {
String zipFilePathStr = dirPath.toString() + ".zip";
Path zipFilePath = Files.createFile(Paths.get(zipFilePathStr));
try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(zipFilePath))) {
Files.list(dirPath)
.filter(filePath-> !Files.isDirectory(filePath))
.forEach(filePath-> {
ZipEntry zipEntry = new ZipEntry(dirPath.relativize(filePath).toString());
try {
zs.putNextEntry(zipEntry);
Files.copy(filePath, zs);
zs.closeEntry();
}
catch (IOException e) {
System.err.println(e);
}
});
}
}
Just for the sake of adding functions to the Date
prototype:
In a mutable fashion / style:
Date.prototype.addDays = function(n) {
this.setDate(this.getDate() + n);
};
// Can call it tomorrow if you want
Date.prototype.nextDay = function() {
this.addDays(1);
};
Date.prototype.addMonths = function(n) {
this.setMonth(this.getMonth() + n);
};
Date.prototype.addYears = function(n) {
this.setFullYear(this.getFullYear() + n);
}
// etc...
var currentDate = new Date();
currentDate.nextDay();
three different approaches:
Classic client/server approach: don't put any database in the shops; simply have the applications access your server. Of course it's better if you set a VPN, but simply wrapping the connection in SSL or ssh is reasonable. Pro: it's the way databases were originally thought. Con: if you have high latency, complex operations could get slow, you might have to use stored procedures to reduce the number of round trips.
replicated master/master: as @Book Of Zeus suggested. Cons: somewhat more complex to setup (especially if you have several shops), breaking in any shop machine could potentially compromise the whole system. Pros: better responsivity as read operations are totally local and write operations are propagated asynchronously.
offline operations + sync step: do all work locally and from time to time (might be once an hour, daily, weekly, whatever) write a summary with all new/modified records from the last sync operation and send to the server. Pros: can work without network, fast, easy to check (if the summary is readable). Cons: you don't have real-time information.
I do understand, that your question was about files stored in MEDIA_ROOT, but sometimes it can be possible to store content in static, when you are not planning to create content of that type anymore.
May be this is a rare case, but anyway - if you have a huge amount of "pictures of the day" for your site - and all these files are on your hard drive?
In that case I see no contra to store such a content in STATIC.
And all becomes really simple:
static
To link to static files that are saved in STATIC_ROOT Django ships with a static template tag. You can use this regardless if you're using RequestContext or not.
{% load static %} <img src="{% static "images/hi.jpg" %}" alt="Hi!" />
copied from Official django 1.4 documentation / Built-in template tags and filters
It seem to ignore the settings for the current active transaction, it only apply settings to a new transaction:
org.springframework.transaction.PlatformTransactionManager TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException Return a currently active transaction or create a new one, according to the specified propagation behavior. Note that parameters like isolation level or timeout will only be applied to new transactions, and thus be ignored when participating in active ones. Furthermore, not all transaction definition settings will be supported by every transaction manager: A proper transaction manager implementation should throw an exception when unsupported settings are encountered. An exception to the above rule is the read-only flag, which should be ignored if no explicit read-only mode is supported. Essentially, the read-only flag is just a hint for potential optimization.
I found an easy solution to your question. I also wanted to use an encoded URL but nothing helped me.
http://example.com/query?q=random%20word%20%A3500%20bank%20%24
to use String example = "random word £500 bank $"; you can you below code.
String example = "random word £500 bank $";
String URL = "http://example.com/query?q=" + example.replaceAll(" ","%20");
What about :
List myList = new ArrayList();
String[] myStringArray = new String[] {"Java", "is", "Cool"};
Collections.addAll(myList, myStringArray);
Add image in repository from upload file option then in README file
![Alt text]("enter image url of repositoryhere")
Outside of character classes, it is conventional not to escape hyphens. If I saw an escaped hyphen outside of a character class, that would suggest to me that it was written by someone who was not very comfortable with regexes.
Inside character classes, I don't think one way is conventional over the other; in my experience, it usually seems to be to put either first or last, as in [-._:]
or [._:-]
, to avoid the backslash; but I've also often seen it escaped instead, as in [._\-:]
, and I wouldn't call that unconventional.
You shouldn't be creating a new Random in method scope. Make it a class member:
public class Foo {
private Random random
public Foo() {
this(System.currentTimeMillis());
}
public Foo(long seed) {
this.random = new Random(seed);
}
public synchronized double getNext() {
return generator.nextDouble();
}
}
This is only an example. I don't think wrapping Random
this way adds any value. Put it in a class of yours that is using it.
If you have a regular submit button, you could add an onclick event to it that does the follow:
document.getElementById('otherForm').submit();
One of the benefit of using the resource file is accessing the resources by names, so the image can change, the image name can change, as long as the resource is kept up to date correct image will show up.
Here is a cleaner approach to accomplish this: Assuming Resources.resx is in 'UI.Images' namespace, add the namespace reference in your xaml like this:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UI="clr-namespace:UI.Images"
Set your Image source like this:
<Image Source={Binding {x:Static UI:Resources.Search}} />
where 'Search' is name of the resource.
Ok guys I found the reason for my encoding issue.
The fault was in my build process. I didn't tell Maven in my pom.xml
file to build the project with the UTF-8 encoding. Therefor Maven just took the default encoding from my system which is MacRoman and build it with the MacRoman encoding.
Luckily Maven is warning you about this when building your project (BUT there is a good chance that the warning disappears to fast from your screen because of all the other messages).
Here is the property you need to set in the pom.xml
file:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
...
</properties>
Thank you guys for all your help. Without you guys I wouldn't be able to figure this out!
Your Customer
class has to be discovered by CDI as a bean. For that you have two options:
Put a bean defining annotation on it. As @Model
is a stereotype it's why it does the trick. A qualifier like @Named
is not a bean defining annotation, reason why it doesn't work
Change the bean discovery mode in your bean archive from the default "annotated" to "all" by adding a beans.xml
file in your jar.
Keep in mind that @Named has only one usage : expose your bean to the UI. Other usages are for bad practice or compatibility with legacy framework.
Two approaches:
When you login: you can to create a copy_my_files.bat
file into your All Programs > Startup
folder with this content (its a plain text document):
xcopy c:\folder\*.* d:\another_folder\.
Use xcopy c:\folder\*.* d:\another_folder\. /Y
to overwrite the file without any prompt.
Everytime a folder changes: if you can to use C#, you can to create a program using FileSystemWatcher
This one works well even in Windows Surface tablets !!!
function detectTouchSupport {
msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture,
touchSupport = (( "ontouchstart" in window ) || msGesture || window.DocumentTouch && document instanceof DocumentTouch);
if(touchSupport) {
$("html").addClass("ci_touch");
}
else {
$("html").addClass("ci_no_touch");
}
}
According to this: http://www.vistax64.com/vista-installation-setup/33219-regsvr32-error-0x80004005.html
Run it in a elevated command prompt.
You are correct in that your list contains a reference to the original dictionary.
a.append(b.copy())
should do the trick.
Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b)
, which makes a deep copy.
If you are working on a Unix system, take advantage of the netrc module in the standard Python library. It reads passwords from a separate text file (.netrc), which has the format decribed here.
Here is a small usage example:
import netrc
# Define which host in the .netrc file to use
HOST = 'mailcluster.loopia.se'
# Read from the .netrc file in your home directory
secrets = netrc.netrc()
username, account, password = secrets.authenticators( HOST )
print username, password
You'll want to use JavaScript's Array splice
method:
var tag_story = [1,3,56,6,8,90],
id_tag = 90,
position = tag_story.indexOf(id_tag);
if ( ~position ) tag_story.splice(position, 1);
P.S. For an explanation of that cool ~
tilde shortcut, see this post:
Using a ~
tilde with indexOf
to check for the existence of an item in an array.
Note: IE < 9 does not support .indexOf()
on arrays. If you want to make sure your code works in IE, you should use jQuery's $.inArray()
:
var tag_story = [1,3,56,6,8,90],
id_tag = 90,
position = $.inArray(id_tag, tag_story);
if ( ~position ) tag_story.splice(position, 1);
If you want to support IE < 9 but don't already have jQuery on the page, there's no need to use it just for $.inArray
. You can use this polyfill instead.
In my case I could not set 'width' and 'height' to null because I'm using TypeScript.
The way I fixed it was by setting them to '100%':
backgroundImage: {
flex: 1,
width: '100%',
height: '100%',
resizeMode: 'cover',
}
Answer provided by Nicholas Krasnov
SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';
Change statement to
DBCC CHECKIDENT('TableName', RESEED, 1)
This will start from 2 (or 1 when you recreate table), but it will never be 0.
In Sql Server you can use it.
DECLARE @UserMaster TABLE(
UserID INT NOT NULL,
UserName varchar(30) NOT NULL
);
INSERT INTO @UserMaster VALUES (1,'Rakesh')
INSERT INTO @UserMaster VALUES (2,'Ashish')
INSERT INTO @UserMaster VALUES (3,'Sagar')
SELECT * FROM @UserMaster
DECLARE @CSV VARCHAR(MAX)
SELECT @CSV = COALESCE(@CSV + ', ', '') + UserName from @UserMaster
SELECT @CSV AS Result
For version v2.2.2 and newer
In version v2.2.2 and up, name property no longer exists and it shouldn't be used to define the route. path should be used instead of name and no leading slash is needed on the path. In this case use path: '404'
instead of path: '/404'
:
{path: '404', component: NotFoundComponent},
{path: '**', redirectTo: '/404'}
For versions older than v2.2.2
you can use {path: '/*path', redirectTo: ['redirectPathName']}
:
{path: '/home/...', name: 'Home', component: HomeComponent}
{path: '/', redirectTo: ['Home']},
{path: '/user/...', name: 'User', component: UserComponent},
{path: '/404', name: 'NotFound', component: NotFoundComponent},
{path: '/*path', redirectTo: ['NotFound']}
if no path matches then redirect to NotFound
path
Math.Floor() :
It gives the largest integer less than or equal to the given number.
Math.Floor(3.45) =3
Math.Floor(-3.45) =-4
Math.Truncate():
It removes the decimal places of the number and replace with zero
Math.Truncate(3.45)=3
Math.Truncate(-3.45)=-3
Also from above examples we can see that floor and truncate are same for positive numbers.
I was facing same issue I have resolved it by removing a field name which was used twice on ajax e.g
jQuery.ajax({
url : '/search-result',
data : {
searchField : searchField,
searchFieldValue : searchField,
nid : nid,
indexName : indexName,
indexType : indexType
},
.....
When a assembly' s AssemblyVersion is changed, If it has strong name, the referencing assemblies need to be recompiled, otherwise the assembly does not load! If it does not have strong name, if not explicitly added to project file, it will not be copied to output directory when build so you may miss depending assemblies, especially after cleaning the output directory.
JUnit 5 (Jupiter) provides three functions to check exception absence/presence:
assertAll?()
Asserts that all supplied executables
do not throw exceptions.
assertDoesNotThrow?()
Asserts that execution of the
supplied executable
/supplier
does not throw any kind of exception.
This function is available
since JUnit 5.2.0 (29 April 2018).
assertThrows?()
Asserts that execution of the supplied executable
throws an exception of the expectedType
and returns the exception.
package test.mycompany.myapp.mymodule;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class MyClassTest {
@Test
void when_string_has_been_constructed_then_myFunction_does_not_throw() {
String myString = "this string has been constructed";
assertAll(() -> MyClass.myFunction(myString));
}
@Test
void when_string_has_been_constructed_then_myFunction_does_not_throw__junit_v520() {
String myString = "this string has been constructed";
assertDoesNotThrow(() -> MyClass.myFunction(myString));
}
@Test
void when_string_is_null_then_myFunction_throws_IllegalArgumentException() {
String myString = null;
assertThrows(
IllegalArgumentException.class,
() -> MyClass.myFunction(myString));
}
}
Much simpler:
position: relative;
left: 50%;
transform: translateX(-50%);
You are now centered in your parent element. You can do that vertically too.
Your expression should already match dashes, because the final - will not be interpreted as a range operator (since the range has no end). To add underscores as well, try:
([A-Za-z0-9_-]+)
Finally I got it:
as3:/usr/local/lib/python2.7/site-packages# cat sitecustomize.py
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
Let me check:
as3:~/ngokevin-site# python
Python 2.7.6 (default, Dec 6 2013, 14:49:02)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.getdefaultencoding()
'utf8'
>>>
The above shows the default encoding of python is utf8
. Then the error is no more.
You also might want to check if the file already exists to avoid replacing the file by accident (unless that is the idea of course:
Dim filepath as String = "C:\my files\2010\SomeFileName.txt"
If Not System.IO.File.Exists(filepath) Then
System.IO.File.Create(filepath).Dispose()
End If
I presume that your problem with background-image
is that it would be inefficient with a source for each image inside a stylesheet. My suggestion is to set the source inline:
<div style = 'background-image: url(image.gif)'></div>
div {
background-repeat: no-repeat;
background-position: 50%;
border-radius: 50%;
width: 100px;
height: 100px;
}
Late, but can be done by using Object.keys like,
var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},_x000D_
ulkeys=document.getElementById('object-keys'),str='';_x000D_
var keys = Object.keys(a);_x000D_
for(i=0,l=keys.length;i<l;i++){_x000D_
str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';_x000D_
}_x000D_
ulkeys.innerHTML=str;
_x000D_
<ul id="object-keys"></ul>
_x000D_
If you are new in JSP/Tomcat don't modify tomcat's xml files.
I assume you have already deployed web application. But to be sure, try these steps: - right click on your web application - select Run As / Run on Server, choose your Tomcat 7
These steps will deploy and run in the browser your application. Another idea to check if your Tomcat works correctly is to find path where tomcat exists (in eclipse plugin), and copy some working WAR file to webapps (not to wtpwebapps), and then try to run the app.
You can try something like this
IFNULL(NULLIF(X, '' ), 0)
Attribute X is assumed to be empty if it is an empty String, so after that you can declare as a zero instead of last value. In another case, it would remain its original value.
Anyway, just to give another way to do that.
Also this is a cause too: If you built a jQuery collection (via .map() or something similar) then you shouldn't use this collection in .ajax()'s data. Because it's still a jQuery object, not plain JavaScript Array. You should use .get() at the and to get plain js array and should use it on the data setting on .ajax().
I feel this question need a bit more details. My answer is inspired from the Android Programming, The Big Nerd Ranch Guide (2nd edition).
By default, JavaScript is off in WebView. You do not always need to have it on, but for some apps, might do require it.
Loading the URL has to be done after configuring the WebView, so you do that last. Before that, you turn JavaScript on by calling getSettings()
to get an instance of WebSettings and calling WebSettings.setJavaScriptEnabled(true)
. WebSettings is the first of the three ways you can modify your WebView. It has various properties you can set, like the user agent string and text size.
After that, you configure your WebViewClient. WebViewClient is an event interface. By providing your own implementation of WebViewClient, you can respond to rendering events. For example, you could detect when the renderer starts loading an image from a particular URL or decide whether to resubmit a POST request to the server.
WebViewClient has many methods you can override, most of which you will not deal with. However, you do need to replace the default WebViewClient’s implementation of shouldOverrideUrlLoading(WebView, String)
. This method determines what will happen when a new URL is loaded in the WebView, like by pressing a link. If you return true, you are saying, “Do not handle this URL, I am handling it myself.” If you return false, you are saying, “Go ahead and load this URL, WebView, I’m not doing anything with it.”
The default implementation fires an implicit intent with the URL, just like you did earlier. Now, though, this would be a severe problem. The first thing some Web Applications does is redirect you to the mobile version of the website. With the default WebViewClient, that means that you are immediately sent to the user’s default web browser. This is just what you are trying to avoid. The fix is simple – just override the default implementation and return false.
Use WebChromeClient to spruce things up Since you are taking the time to create your own WebView, let’s spruce it up a bit by adding a progress bar and updating the toolbar’s subtitle with the title of the loaded page.
To hook up the ProgressBar, you will use the second callback on WebView: WebChromeClient
.
WebViewClient is an interface for responding to rendering events; WebChromeClient is an event interface for reacting to events that should change elements of chrome around the browser. This includes JavaScript alerts, favicons, and of course updates for loading progress and the title of the current page.
Hook it up in onCreateView(…)
. Using WebChromeClient to spruce things up
Progress updates and title updates each have their own callback method,
onProgressChanged(WebView, int)
and onReceivedTitle(WebView, String)
. The progress you receive from onProgressChanged(WebView, int)
is an integer from 0 to 100. If it is 100, you know
that the page is done loading, so you hide the ProgressBar by setting its visibility to View.GONE
.
Disclaimer: This information was taken from Android Programming: The Big Nerd Ranch Guide with permission from the authors. For more information on this book or to purchase a copy, please visit bignerdranch.com.
Upload your file to Skydrive and then right click and select "Embed". They will provide iframe snippet which you can paste in your html. This works flawlessly.
Source: Office.com
You can use:
<asp:textbox id="textBox1" style="text-align:center"></asp:textbox>
Or this:
textbox.Style["text-align"] = "center"; //right, left
First, There is no such css-changes event out of the box, but you can create one by your own, as onchange
is for :input
elements only. not for css changes.
There are two ways to track css changes.
DOMAttrModified
mutation event. But it's deprecated, so I'll skip on it.First way:
var $element = $("#elementId");
var lastHeight = $("#elementId").css('height');
function checkForChanges()
{
if ($element.css('height') != lastHeight)
{
alert('xxx');
lastHeight = $element.css('height');
}
setTimeout(checkForChanges, 500);
}
Second way:
$('#mainContent').bind('heightChange', function(){
alert('xxx');
});
$("#btnSample1").click(function() {
$("#mainContent").css('height', '400px');
$("#mainContent").trigger('heightChange'); //<====
...
});
If you control the css changes, the second option is a lot more elegant and efficient way of doing it.
Documentations:
The best way to add different objects into same container is to use make_shared, vector, and range based loop and you will have a nice, clean and "readable" code!
typedef std::shared_ptr<gate> Ptr
vector<Ptr> myConatiner;
auto andGate = std::make_shared<ANDgate>();
myConatiner.push_back(andGate );
auto orGate= std::make_shared<ORgate>();
myConatiner.push_back(orGate);
for (auto& element : myConatiner)
element->run();
I just had a quick look at your example, but if i understood it the right way you're trying to add 404 routes to dynamic segments. I had the same issue a couple of days ago, found #458 and #1103 and ended up with a hand made check within the render function:
if (!place) return <NotFound />;
hope that helps!
While you should ideally highlight the code which is causing an error and post that within your question, the error is because you are trying to get the inner HTML of the 'status' element:
var idPost=document.getElementById("status").innerHTML;
However the 'status' element does not exist within your HTML - either add the necessary element or change the ID you are trying to locate to point to a valid element.
Made a simple implementation of what I believe to be what you want to achieve. You can use the class later
with the following arguments:
You can change std::chrono::milliseconds
to std::chrono::nanoseconds
or microseconds
for even higher precision and add a second int and a for loop to specify for how many times to run the code.
Here you go, enjoy:
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
class later
{
public:
template <class callable, class... arguments>
later(int after, bool async, callable&& f, arguments&&... args)
{
std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
if (async)
{
std::thread([after, task]() {
std::this_thread::sleep_for(std::chrono::milliseconds(after));
task();
}).detach();
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(after));
task();
}
}
};
void test1(void)
{
return;
}
void test2(int a)
{
printf("%i\n", a);
return;
}
int main()
{
later later_test1(1000, false, &test1);
later later_test2(1000, false, &test2, 101);
return 0;
}
Outputs after two seconds:
101
As so often with SQL-related question, it depends on the DBMS. Some DBMS allow you to combine ALTER table operations separated by commas. For example...
Informix syntax:
ALTER TABLE one
ADD two_id INTEGER,
ADD CONSTRAINT FOREIGN KEY(two_id) REFERENCES two(id);
The syntax for IBM DB2 LUW is similar, repeating the keyword ADD but (if I read the diagram correctly) not requiring a comma to separate the added items.
Microsoft SQL Server syntax:
ALTER TABLE one
ADD two_id INTEGER,
FOREIGN KEY(two_id) REFERENCES two(id);
Some others do not allow you to combine ALTER TABLE operations like that. Standard SQL only allows a single operation in the ALTER TABLE statement, so in Standard SQL, it has to be done in two steps.
To get your radio button to list horizontally , just add
RepeatDirection="Horizontal"
to your .aspx file where the asp:radiobuttonlist is being declared.
with open(filename) as file:
words = file.read().split()
Its a List of all words in your file.
import re
with open(filename) as file:
words = re.findall(r"([a-zA-Z\-]+)", file.read())
You could do this:
(Note! This is CSS3 and the browser support = good!! )
p {
text-overflow: ellipsis; /* will make [...] at the end */
width: 370px; /* change to your preferences */
white-space: nowrap; /* paragraph to one line */
overflow:hidden; /* older browsers */
}
As explained here by Filip - http://www.filipekberg.se/2011/10/02/adding-properties-and-methods-to-an-expandoobject-dynamicly/
You can add a method too at runtime.
x.Add("Shout", new Action(() => { Console.WriteLine("Hellooo!!!"); }));
x.Shout();
try this,it should work fine
this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));
Add ScalarsConverterFactory to retrofit:
in gradle:
implementation'com.squareup.retrofit2:converter-scalars:2.5.0'
your retrofit:
retrofit = new Retrofit.Builder()
.baseUrl(WEB_DOMAIN_MAIN)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
change your call interface @Body parameter to String, don't forget to add @Headers("Content-Type: application/json")
:
@Headers("Content-Type: application/json")
@POST("/api/getUsers")
Call<List<Users>> getUsers(@Body String rawJsonString);
now you can post raw json.
git reset --hard
This command will completely remove all the local changes from your local repository. This is the best way to avoid conflicts during pull command, only if you don't want to keep your local changes at all.
If you want to pull the new changes from remote and want to ignore the local changes during this pull then,
git stash
It will stash all the local changes, now you can pull the remote changes,
git pull
Now, you can bring back your local changes by,
git stash pop
cd
to a different one.ssh-keygen
/c/Users/YourUserName/.ssh/id_rsa.pub
p.s.: If you installed git with bash integration (like me) open "Git Bash" instead of "cmd" on first step
There is no library function for that. You have to code by your own.
for _, value := range myconfig {
if value.Key == "key1" {
// logic
}
}
Working code: https://play.golang.org/p/IJIhYWROP_
package main
import (
"encoding/json"
"fmt"
)
func main() {
type Config struct {
Key string
Value string
}
var respbody = []byte(`[
{"Key":"Key1", "Value":"Value1"},
{"Key":"Key2", "Value":"Value2"}
]`)
var myconfig []Config
err := json.Unmarshal(respbody, &myconfig)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v\n", myconfig)
for _, v := range myconfig {
if v.Key == "Key1" {
fmt.Println("Value: ", v.Value)
}
}
}
Just like any other environment variable, with SET
:
SET PATH=%PATH%;c:\whatever\else
If you want to have a little safety check built in first, check to see if the new path exists first:
IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else
If you want that to be local to that batch file, use setlocal
:
setlocal
set PATH=...
set OTHERTHING=...
@REM Rest of your script
Read the docs carefully for setlocal
/endlocal
, and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.
The Syntax page should get you started with the basics.
If you want to display date time on view without model, just write this:
Date : @DateTime.Now
The output will be:
Date : 16-Aug-17 2:32:10 PM
I previously had the same issue, but I realized that I didn't include the "app.js
" (the main application) inside my main page (index.html
).
So even when you include all the dependencies required by AngularJS, you might end up with that error in the console. So always make sure to include the necessary files inside your main page and you shouldn't have that issue.
Hope this helps.
https://developers.google.com/chrome-developer-tools/docs/settings
I'd reconsider the strategy to use only a single regular expression. Sure it's a nice game to come up with one single regular expression that does it all. But in terms of maintainabilty you are about to shoot yourself in both feet.
Use the command line, not the Python shell (DOS, PowerShell in Windows).
C:\Program Files\Python2.7\Scripts> pip install XYZ
If you installed Python into your PATH using the latest installers, you don't need to be in that folder to run pip
Terminal in Mac or Linux
$ pip install XYZ
I've made a little modification of Rafael's code for MKMapView Category.
- (void)zoomToFitMapAnnotations {
if ([self.annotations count] == 0)
return;
CLLocationCoordinate2D topLeftCoord;
topLeftCoord.latitude = -90;
topLeftCoord.longitude = 180;
CLLocationCoordinate2D bottomRightCoord;
bottomRightCoord.latitude = 90;
bottomRightCoord.longitude = -180;
for (id <MKAnnotation> annotation in self.annotations) {
topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
}
MKCoordinateRegion region;
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides
[self setRegion:[self regionThatFits:region] animated:YES];
}
The bson extension message is just a warning, I get it all the time in my nodejs application.
Things to check:
I believe I have a much simpeler solution for this.
public class MyFragment extends Fragment{
private String mTitle;
private List<MyObject> mObjects;
public static MyFragment newInstance(String title, List<MyObject> objects)
MyFragment myFrag = new MyFragment();
myFrag.mTitle = title;
myFrag.mObjects = objects;
return myFrag;
}
- Another Update -
Since Twitter Bootstrap version 2.0 - which saw the removal of the .container-fluid
class - it has not been possible to implement a two column fixed-fluid layout using just the bootstrap classes - however I have updated my answer to include some small CSS changes that can be made in your own CSS code that will make this possible
It is possible to implement a fixed-fluid structure using the CSS found below and slightly modified HTML code taken from the Twitter Bootstrap Scaffolding : layouts documentation page:
<div class="container-fluid fill">
<div class="row-fluid">
<div class="fixed"> <!-- we want this div to be fixed width -->
...
</div>
<div class="hero-unit filler"> <!-- we have removed spanX class -->
...
</div>
</div>
</div>
/* CSS for fixed-fluid layout */
.fixed {
width: 150px; /* the fixed width required */
float: left;
}
.fixed + div {
margin-left: 150px; /* must match the fixed width in the .fixed class */
overflow: hidden;
}
/* CSS to ensure sidebar and content are same height (optional) */
html, body {
height: 100%;
}
.fill {
min-height: 100%;
position: relative;
}
.filler:after{
background-color:inherit;
bottom: 0;
content: "";
height: auto;
min-height: 100%;
left: 0;
margin:inherit;
right: 0;
position: absolute;
top: 0;
width: inherit;
z-index: -1;
}
I have kept the answer below - even though the edit to support 2.0 made it a fluid-fluid solution - as it explains the concepts behind making the sidebar and content the same height (a significant part of the askers question as identified in the comments)
Update As pointed out by @JasonCapriotti in the comments, the original answer to this question (created for v1.0) did not work in Bootstrap 2.0. For this reason, I have updated the answer to support Bootstrap 2.0
To ensure that the main content fills at least 100% of the screen height, we need to set the height of the html
and body
to 100% and create a new css class called .fill
which has a minimum-height of 100%:
html, body {
height: 100%;
}
.fill {
min-height: 100%;
}
We can then add the .fill
class to any element that we need to take up 100% of the sceen height. In this case we add it to the first div:
<div class="container-fluid fill">
...
</div>
To ensure that the Sidebar and the Content columns have the same height is very difficult and unnecessary. Instead we can use the ::after
pseudo selector to add a filler
element that will give the illusion that the two columns have the same height:
.filler::after {
background-color: inherit;
bottom: 0;
content: "";
right: 0;
position: absolute;
top: 0;
width: inherit;
z-index: -1;
}
To make sure that the .filler
element is positioned relatively to the .fill
element we need to add position: relative
to .fill
:
.fill {
min-height: 100%;
position: relative;
}
And finally add the .filler
style to the HTML:
HTML
<div class="container-fluid fill">
<div class="row-fluid">
<div class="span3">
...
</div>
<div class="span9 hero-unit filler">
...
</div>
</div>
</div>
Notes
right: 0
to left: 0
.This may be of help to a few who are struggling like I was:
var data = myform.getRange("A:AA").getValues().pop();
var myvariable1 = data[4];
var myvariable2 = data[7];
I was getting this same error and spent a day and a half trying to find a solution. Naomi's answer lead me to the solution I needed.
My input (type=button) had an attribute name
that was identical to a function name that was being called by the onClick event. Once I changed the attribute name
everything worked.
<input type="button" name="clearEmployer" onClick="clearEmployer();">
changed to:
<input type="button" name="clearEmployerBtn" onClick="clearEmployer();">
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="com.tridenthyundai.ains" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
process.terminate() doesn't work when using shell=True
. This answer will help you.
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
You can accomplished your requirement easily by using Newtonsoft.Json library. I am writing down the one example below have a look into it.
Class for the type of object you receive:
public class User
{
public int ID { get; set; }
public string Name { get; set; }
}
Code:
static void Main(string[] args)
{
string json = "{\"ID\": 1, \"Name\": \"Abdullah\"}";
User user = JsonConvert.DeserializeObject<User>(json);
Console.ReadKey();
}
this is a very simple way to parse your json.
You should probably make the Child as functional component if it does not maintain any state and simply renders the props and then call it from the parent. Alternative to this is that you can use hooks with the functional component (useState) which will cause stateless component to re-render.
Also you should not alter the propas as they are immutable. Maintain state of the component.
Child = ({bar}) => (bar);
The reason your URL is being rewritten to file///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf
is because you specified http://file://
The http://
at the beginning is the protocol being used, and your browser is stripping out the second colon (:) because it is invalid.
Note
If you link to something like
<a href="file:///K:/yourfile.pdf">yourfile.pdf</a>
The above represents a link to a file called k:/yourfile.pdf
on the k: drive on the machine on which you are viewing the URL.
You can do this, for example the below creates a link to C:\temp\test.pdf
<a href="file:///C:/Temp/test.pdf">test.pdf</a>
By specifying file:// you are indicating that this is a local resource. This resource is NOT on the internet.
Most people do not have a K:/ drive.
But, if this is what you are trying to achieve, that's fine, but this is not how a "typical" link on a web page works, and you shouldn't being doing this unless everyone who is going to access your link has access to the (same?) K:/drive (this might be the case with a shared network drive).
You could try
<a href="file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
Note that http://file:///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf
is a malformed
Use url as:https://graph.facebook.com/user_id/picture?type=square in src of img tag. type may be small,large.
ADB will often fail if there is a newline in adb_usb.ini
. Remove it, restart it, and that will often solve the problem (at least for me anyway).
Subqueries have ability to calculate aggregation functions on a fly. E.g. Find minimal price of the book and get all books which are sold with this price. 1) Using Subqueries:
SELECT titles, price
FROM Books, Orders
WHERE price =
(SELECT MIN(price)
FROM Orders) AND (Books.ID=Orders.ID);
2) using JOINs
SELECT MIN(price)
FROM Orders;
-----------------
2.99
SELECT titles, price
FROM Books b
INNER JOIN Orders o
ON b.ID = o.ID
WHERE o.price = 2.99;
str.replace()
does fixed replacements. Use re.sub()
instead.
It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment
as you can see above).
Try checking to see if Hibernate core is put in as dependency:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.11.Final</version>
<scope>compile</scope>
</dependency>
From Rails Guides:
If you wish for a migration to do something that Active Record doesn’t know how to reverse, you can use
reversible
:
class ChangeTablenameFieldname < ActiveRecord::Migration[5.1]
def change
reversible do |dir|
change_table :tablename do |t|
dir.up { t.change :fieldname, :date }
dir.down { t.change :fieldname, :datetime }
end
end
end
end
Since jQuery AJAX requests fail if they are cross-domain, you can use cURL (in PHP) to set up a proxy server.
Suppose a PHP file responder.php has these contents:
$url = "https://www.google.com";
$ch = curl_init( $url );
curl_set_opt($ch, CURLOPT_RETURNTRANSFER, "true")
$response= curl_exec( $ch );
curl_close( $ch );
return $response;
Your AJAX request should be to this responder.php file so that it executes the cross-domain request.
In terminal : rvm gemset use global
Microsoft has an article about this issue. It goes through it all step by step.
In short it involves starting up the instance of sqlserver with -m
like all the other answers suggest. However Microsoft provides slightly more detailed instructions.
From the Start page, start SQL Server Management Studio. On the View menu, select Registered Servers. (If your server is not already registered, right-click Local Server Groups, point to Tasks, and then click Register Local Servers.)
In the Registered Servers area, right-click your server, and then click SQL Server Configuration Manager. This should ask for permission to run as administrator, and then open the Configuration Manager program.
Close Management Studio.
In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, find your instance of SQL Server. (The default instance of SQL Server includes (MSSQLSERVER) after the computer name. Named instances appear in upper case with the same name that they have in Registered Servers.) Right-click the instance of SQL Server, and then click Properties.
On the Startup Parameters tab, in the Specify a startup parameter box, type -m and then click Add. (That's a dash then lower case letter m.)
Note
For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Be careful not to change any of the existing parameters. At the very end, add a new parameter ;-m and then click OK. (That's a semi-colon then a dash then lower case letter m.)
Click OK, and after the message to restart, right-click your server name, and then click Restart.
After SQL Server has restarted your server will be in single-user mode. Make sure that that SQL Server Agent is not running. If started, it will take your only connection.
On the Windows 8 start screen, right-click the icon for Management Studio. At the bottom of the screen, select Run as administrator. (This will pass your administrator credentials to SSMS.)
Note
For earlier versions of Windows, the Run as administrator option appears as a sub-menu.
In some configurations, SSMS will attempt to make several connections. Multiple connections will fail because SQL Server is in single-user mode. You can select one of the following actions to perform. Do one of the following.
a) Connect with Object Explorer using Windows Authentication (which includes your Administrator credentials). Expand Security, expand Logins, and double-click your own login. On the Server Roles page, select sysadmin, and then click OK.
b) Instead of connecting with Object Explorer, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). (You can only connect this way if you did not connect with Object Explorer.) Execute code such as the following to add a new Windows Authentication login that is a member of the sysadmin fixed server role. The following example adds a domain user named CONTOSO\PatK.
CREATE LOGIN [CONTOSO\PatK] FROM WINDOWS; ALTER SERVER ROLE sysadmin ADD MEMBER [CONTOSO\PatK];
c) If your SQL Server is running in mixed authentication mode, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Execute code such as the following to create a new SQL Server Authentication login that is a member of the sysadmin fixed server role.
CREATE LOGIN TempLogin WITH PASSWORD = '************'; ALTER SERVER ROLE sysadmin ADD MEMBER TempLogin;
Warning:
Replace ************ with a strong password.
d) If your SQL Server is running in mixed authentication mode and you want to reset the password of the sa account, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Change the password of the sa account with the following syntax.
ALTER LOGIN sa WITH PASSWORD = '************'; Warning
Replace ************ with a strong password.
The following steps now change SQL Server back to multi-user mode. Close SSMS.
In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, right-click the instance of SQL Server, and then click Properties.
On the Startup Parameters tab, in the Existing parameters box, select -m and then click Remove.
Note
For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Remove the ;-m which you added earlier, and then click OK.
Right-click your server name, and then click Restart.
Now you should be able to connect normally with one of the accounts which is now a member of the sysadmin fixed server role.