Claiming that the C++ compiler can produce more optimal code than a competent assembly language programmer is a very bad mistake. And especially in this case. The human always can make the code better than the compiler can, and this particular situation is a good illustration of this claim.
The timing difference you're seeing is because the assembly code in the question is very far from optimal in the inner loops.
(The below code is 32-bit, but can be easily converted to 64-bit)
For example, the sequence function can be optimized to only 5 instructions:
.seq:
inc esi ; counter
lea edx, [3*eax+1] ; edx = 3*n+1
shr eax, 1 ; eax = n/2
cmovc eax, edx ; if CF eax = edx
jnz .seq ; jmp if n<>1
The whole code looks like:
include "%lib%/freshlib.inc"
@BinaryType console, compact
options.DebugMode = 1
include "%lib%/freshlib.asm"
start:
InitializeAll
mov ecx, 999999
xor edi, edi ; max
xor ebx, ebx ; max i
.main_loop:
xor esi, esi
mov eax, ecx
.seq:
inc esi ; counter
lea edx, [3*eax+1] ; edx = 3*n+1
shr eax, 1 ; eax = n/2
cmovc eax, edx ; if CF eax = edx
jnz .seq ; jmp if n<>1
cmp edi, esi
cmovb edi, esi
cmovb ebx, ecx
dec ecx
jnz .main_loop
OutputValue "Max sequence: ", edi, 10, -1
OutputValue "Max index: ", ebx, 10, -1
FinalizeAll
stdcall TerminateAll, 0
In order to compile this code, FreshLib is needed.
In my tests, (1 GHz AMD A4-1200 processor), the above code is approximately four times faster than the C++ code from the question (when compiled with -O0
: 430 ms vs. 1900 ms), and more than two times faster (430 ms vs. 830 ms) when the C++ code is compiled with -O3
.
The output of both programs is the same: max sequence = 525 on i = 837799.
try this
<Button
android:id="@+id/btn_location"
android:layout_width="121dp"
android:layout_height="38dp"
android:layout_gravity="center"
android:layout_marginBottom="24dp"
android:layout_marginTop="24dp"
android:foreground="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:background="@drawable/btn_corner"
android:gravity="center_vertical|center_horizontal"
android:paddingLeft="13dp"
android:paddingRight="13dp"
android:text="Save"
android:textColor="@color/color_white" />
Is there any way that I can start android emulator for intel x86 atom Without hardware acceleration on windows 8
Not with the standard Android SDK emulator, as it requires Intel's HAXM, and HAXM wants virtualization extensions to be enabled.
Whether Genymotion or something else from another independent developer can support your desired combination, I cannot say.
Android SDK
Installing the Android SDK is also necessary. The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android.
Cordova requires the ANDROID_HOME
environment variable to be set. This should point to the [ANDROID_SDK_DIR]\android-sdk
directory (for example c:\android\android-sdk).
Next, update your PATH to include the tools/ and platform-tools/ folder in that folder. So, using ANDROID_HOME
, you would add both %ANDROID_HOME%\tools
and %ANDROID_HOME%\platform-tools
.
Reference : http://ionicframework.com/docs/v1/guide/installation.html
You can't call free
on the pointers returned from strsep
. Those are not individually allocated strings, but just pointers into the string s
that you've already allocated. When you're done with s
altogether, you should free it, but you do not have to do that with the return values of strsep
.
adb kill-server will kill all emulators and restart the server clean.
First add next code in your sp:
BEGIN
dbms_output.enable();
dbms_output.put_line ('TEST LINE');
END;
Compile your code in your Oracle SQL developer. So go to Menu View--> dbms output. Click on Icon Green Plus and select your schema. Run your sp now.
I realize that this is an old question but perhaps someone will find my code sample useful. This code encodes a file in Base64 then decodes it and saves it in a new location.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.apache.commons.codec.binary.Base64;
public class Base64Example {
public static void main(String[] args) {
Base64Example tempObject = new Base64Example();
// convert file to regular byte array
byte[] codedFile = tempObject.convertFileToByteArray("your_input_file_path");
// encoded file in Base64
byte[] encodedFile = Base64.encodeBase64(codedFile);
// print out the byte array
System.out.println(Arrays.toString(encodedFile));
// print the encoded String
System.out.println(encodedFile);
// decode file back to regular byte array
byte[] decodedByteArray = Base64.decodeBase64(encodedFile);
// save decoded byte array to a file
boolean success = tempObject.saveFileFromByteArray("your_output_file_path", decodedByteArray);
// print out success
System.out.println("success : " + success);
}
public byte[] convertFileToByteArray(String filePath) {
Path path = Paths.get(filePath);
byte[] codedFile = null;
try {
codedFile = Files.readAllBytes(path);
} catch (IOException e) {
e.printStackTrace();
}
return codedFile;
}
public boolean saveFileFromByteArray(String filePath, byte[] decodedByteArray) {
boolean success = false;
Path path = Paths.get(filePath);
try {
Files.write(path, decodedByteArray);
success = true;
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
}
MappedBy signals hibernate that the key for the relationship is on the other side.
This means that although you link 2 tables together, only 1 of those tables has a foreign key constraint to the other one. MappedBy allows you to still link from the table not containing the constraint to the other table.
To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified all '.lib' files & there names for current project.
So, Developer has to specify external dependencies for Project as below..
1. Select Project in Solution explorer.
2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".
3. Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".
add new server (tomcat) with different location. if i am not make mistake you are run multiple project with same tomcat and add same tomcat server on same location ..
add new tomcat for each new workspace.
It means that you have a memory error. You may be trying to free
a pointer that wasn't allocated by malloc
(or delete
an object that wasn't created by new
) or you may be trying to free
/delete
such an object more than once. You may be overflowing a buffer or otherwise writing to memory to which you shouldn't be writing, causing heap corruption.
Any number of programming errors can cause this problem. You need to use a debugger, get a backtrace, and see what your program is doing when the error occurs. If that fails and you determine you have corrupted the heap at some previous point in time, you may be in for some painful debugging (it may not be too painful if the project is small enough that you can tackle it piece by piece).
All of the above might be true, however for me "online-updating" of figures only works with some backends, specifically wx
. You just might try to change to this, e.g. by starting ipython/pylab by ipython --pylab=wx
! Good luck!
For Python 3.6+
and for any list
rather than just int
s, as well as using the entire width of your console window and not crossing over to a new line, you could use the following:
note: please be informed, that the function get_console_with()
will work only on Linux based systems, and as such you have to rewrite it to work on Windows.
import os
import time
def get_console_width():
"""Returns the width of console.
NOTE: The below implementation works only on Linux-based operating systems.
If you wish to use it on another OS, please make sure to modify it appropriately.
"""
return int(os.popen('stty size', 'r').read().split()[1])
def range_with_progress(list_of_elements):
"""Iterate through list with a progress bar shown in console."""
# Get the total number of elements of the given list.
total = len(list_of_elements)
# Get the width of currently used console. Subtract 2 from the value for the
# edge characters "[" and "]"
max_width = get_console_width() - 2
# Start iterating over the list.
for index, element in enumerate(list_of_elements):
# Compute how many characters should be printed as "done". It is simply
# a percentage of work done multiplied by the width of the console. That
# is: if we're on element 50 out of 100, that means we're 50% done, or
# 0.5, and we should mark half of the entire console as "done".
done = int(index / total * max_width)
# Whatever is left, should be printed as "unfinished"
remaining = max_width - done
# Print to the console.
print(f'[{done * "#"}{remaining * "."}]', end='\r')
# yield the element to work with it
yield element
# Finally, print the full line. If you wish, you can also print whitespace
# so that the progress bar disappears once you are done. In that case do not
# forget to add the "end" parameter to print function.
print(f'[{max_width * "#"}]')
if __name__ == '__main__':
list_of_elements = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
for e in range_with_progress(list_of_elements):
time.sleep(0.2)
there are major 4 steps
1. copy the .android folder to your desired location as i did in D:\Android\.android
2. set ANDROID_AVD_HOME in environment variables like ANDROID_AVD_HOME
D:\Android\.android\avd
3. change avd name.ini file contents with new location like
avd.ini.encoding=UTF-8
path=D:\Android\.android\avd\Pixel_2_API_29.avd
path.rel=avd\Pixel_2_API_29.avd
target=android-29
4. restart android studio
Was asked here before: Unix command to find lines common in two files
You could also try with perl (credit goes here)
perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/' file1 file2
Here is how its done in Angular 6
<li *ngFor="let user of userObservable ; first as isFirst">
<span *ngIf="isFirst">default</span>
</li>
Note the change from let first = first
to first as isFirst
Use the FolderExists
method of the Scripting
object.
Public Function dirExists(s_directory As String) As Boolean
Dim oFSO As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
dirExists = oFSO.FolderExists(s_directory)
End Function
You just need a:
replaceAll("\\s{2,}", " ").trim();
where you match one or more spaces and replace them with a single space and then trim whitespaces at the beginning and end (you could actually invert by first trimming and then matching to make the regex quicker as someone pointed out).
To test this out quickly try:
System.out.println(new String(" hello there ").trim().replaceAll("\\s{2,}", " "));
and it will return:
"hello there"
The best way is not to write any initializing statements. This is because if you write
int a[]=new int[3]
then by default, in Java all the values of array i.e. a[0]
, a[1]
and a[2]
are initialized to 0
! Regarding the local variable hiding a field, post your entire code for us to come to conclusion.
I am using the following test to see if strings have been urlencoded:
if(urlencode($str) != str_replace(['%','+'], ['%25','%2B'], $str))
If a string has already been urlencoded, the only characters that will changed by double encoding are % (which starts all encoded character strings) and + (which replaces spaces.) Change them back and you should have the original string.
Let me know if this works for you.
For me, the following is working and running activiti server as well as opening the explorer in browser (with the help of zb226's answer and comment);
START "runas /user:administrator" cmd /K "cd C:\activiti-5.9\setup & ant demo.start"
START /wait localhost:8080/activiti-explorer
Best performance method
sed '5q;d' file
Because sed
stops reading any lines after the 5th one
Update experiment from Mr. Roger Dueck
I installed wcanadian-insane (6.6MB) and compared sed -n 1p /usr/share/dict/words and sed '1q;d' /usr/share/dict/words using the time command; the first took 0.043s, the second only 0.002s, so using 'q' is definitely a performance improvement!
Use the below class to Generate a Salt first. Each user needs to have a different salt, we can save it in the database along with the other user properties. The rounds value decides the number of times the password will be hashed.
public class HashSaltWithRounds
{
int saltLength = 32;
public byte[] GenerateSalt()
{
using (var randomNumberGenerator = new RNGCryptoServiceProvider())
{
var randomNumber = new byte[saltLength];
randomNumberGenerator.GetBytes(randomNumber);
return randomNumber;
}
}
public string HashDataWithRounds(byte[] password, byte[] salt, int rounds)
{
using(var rfc2898= new Rfc2898DeriveBytes(password, salt, rounds))
{
return Convert.ToBase64String(rfc2898.GetBytes(32));
}
}
}
We can call it from a console application as follows. I have hashed the password twice using the same salt.
public class Program
{
public static void Main(string[] args)
{
int numberOfIterations = 99;
var hashFunction = new HashSaltWithRounds();
string password = "Your Password Here";
byte[] salt = hashFunction.GenerateSalt();
var hashedPassword1 = hashFunction.HashDataWithRounds(Encoding.UTF8.GetBytes(password), salt, numberOfIterations);
var hashedPassword2 = hashFunction.HashDataWithRounds(Encoding.UTF8.GetBytes(password), salt, numberOfIterations);
Console.WriteLine($"hashedPassword1 :{hashedPassword1}");
Console.WriteLine($"hashedPassword2 :{hashedPassword2}");
Console.WriteLine(hashedPassword1.Equals(hashedPassword2));
Console.ReadLine();
}
}
If you want only the scheme and authority part of the request (protocol, host and port) use
Request.Url.GetLeftPart(UriPartial.Authority)
If you use JAX-WS, the following works for me:
//Get Web service Port
WSTestService wsService = new WSTestService();
WSTest wsPort = wsService.getWSTestPort();
// Add username and password for Basic Authentication
Map<String, Object> reqContext = ((BindingProvider)
wsPort).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "username");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password");
Utilizing/Copying Darin Dimitrov's great response, this is how to access a custom attribute on a property and not a class:
The decorated property [of class Foo
]:
[MyCustomAttribute(SomeProperty = "This is a custom property")]
public string MyProperty { get; set; }
Fetching it:
PropertyInfo propertyInfo = typeof(Foo).GetProperty(propertyToCheck);
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
}
You can throw this in a loop and use reflection to access this custom attribute on each property of class Foo
, as well:
foreach (PropertyInfo propertyInfo in Foo.GetType().GetProperties())
{
string propertyName = propertyInfo.Name;
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
// Just in case you have a property without this annotation
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
// TODO: whatever you need with this propertyValue
}
}
Major thanks to you, Darin!!
Was following the documentations - Apache Log4j2 Configuratoin and Apache Log4j2 Maven in configuring log4j2 with yaml. As per the documentation, the following maven dependencies are required:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.1</version>
</dependency>
and
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.8.6</version>
</dependency>
Just adding these didn't pick the configuration and always gave error. The way of debugging configuration by adding -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=TRACE
helped in seeing the logs. Later had to download the source using Maven and debugging helped in understanding the depended classes of log4j2. They are listed in org.apache.logging.log4j.core.config.yaml.YamlConfigurationFactory
:
com.fasterxml.jackson.databind.ObjectMapper
com.fasterxml.jackson.databind.JsonNode
com.fasterxml.jackson.core.JsonParser
com.fasterxml.jackson.dataformat.yaml.YAMLFactory
Adding dependency mapping for jackson-dataformat-yaml
will not have the first two classes. Hence, add the jackson-databind
dependency to get yaml configuration working:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.6</version>
</dependency>
You may add the version by referring to the Test Dependencies
section of log4j-api
version item from MVN Repository. E.g. for 2.8.1 version of log4j-api, refer this link and locate the jackson-databind
version.
Moreover, you can use the below Java code to check if the classes are available in the classpath:
System.out.println(ClassLoader.getSystemResource("log4j2.yml")); //Check if file is available in CP
ClassLoader cl = Thread.currentThread().getContextClassLoader(); //Code as in log4j2 API. Version: 2.8.1
String [] classes = {"com.fasterxml.jackson.databind.ObjectMapper",
"com.fasterxml.jackson.databind.JsonNode",
"com.fasterxml.jackson.core.JsonParser",
"com.fasterxml.jackson.dataformat.yaml.YAMLFactory"};
for(String className : classes) {
cl.loadClass(className);
}
For Mac Users
I am using Mac and I was facing the same problem while I was trying to push a project from Android Studio. The reason for that is another user had previously logged into GitHub and his credentials were saved in Keychain Access.
The solution is to delete all the information store in keychain for that process
$results = DB::table('rooms')
->distinct()
->leftJoin('bookings', function($join)
{
$join->on('rooms.id', '=', 'bookings.room_type_id');
$join->on('arrival','>=',DB::raw("'2012-05-01'"));
$join->on('arrival','<=',DB::raw("'2012-05-10'"));
$join->on('departure','>=',DB::raw("'2012-05-01'"));
$join->on('departure','<=',DB::raw("'2012-05-10'"));
})
->where('bookings.room_type_id', '=', NULL)
->get();
Not quite sure if the between clause can be added to the join in laravel.
Notes:
DB::raw()
instructs Laravel not to put back quotes.on()
will add AND
condition and orOn()
will add OR
condition.In case you just want to split by x number of lines each file, the given answers about split
are OK. But, i am curious about no one paid attention to requirements:
I can't do that without "wc + cut", but I'm using that:
split -l $(expr `wc $filename | cut -d ' ' -f3` / $chunks) $filename
This can be easily added to your bashrc functions so you can just invoke it passing filename and chunks:
split -l $(expr `wc $1 | cut -d ' ' -f3` / $2) $1
In case you want just x chunks without remainder in extra file, just adapt the formula to sum it (chunks - 1) on each file. I do use this approach because usually i just want x number of files rather than x lines per file:
split -l $(expr `wc $1 | cut -d ' ' -f3` / $2 + `expr $2 - 1`) $1
You can add that to a script and call it your "ninja way", because if nothing suites your needs, you can build it :-)
Install Proxifier in your host computer. Setup proxifier to use your proxy. You don't need to do anything else. You will be fine. Proxifier traps the calls from the system (including the android emulator) and route it through the configured proxy.
If you are using Microsoft Drivers 3.1, 3.0, and 2.0.
Please check your PHP version already install with IIS.
Use this script to check the php version:
<?php echo phpinfo(); ?>
OR
If you have installed PHP Manager in IIS using web platform Installer you can check the version from it.
Then:
If you are using new PHP version (5.6) please download Drivers from here
For PHP version Lower than 5.6 - please download Drivers from here
Then use the PHP Manager to add that downloaded drivers into php config
file.You can do it as shown below (browse the files and press OK).
Then Restart the IIS Server
If this method not work please change the php version and try to run your php script.
Tip:Change the php version
to lower and try to understand what happened.then you can download relevant drivers.
In ES8 using moment, now and start being moment objects.
const duration = moment.duration(now.diff(start));
const timespan = duration.get("hours").toString().padStart(2, '0') +":"+ duration.get("minutes").toString().padStart(2, '0') +":"+ duration.get("seconds").toString().padStart(2, '0');
It is indeed much less simple than it seems :-) Nick's suggestion is a good one.
To get started, keep in mind that any worthwhile comparison method will essentially work by converting the images into a different form -- a form which makes it easier to pick similar features out. Usually, this stuff doesn't make for very light reading ...
One of the simplest examples I can think of is simply using the color space of each image. If two images have highly similar color distributions, then you can be reasonably sure that they show the same thing. At least, you can have enough certainty to flag it, or do more testing. Comparing images in color space will also resist things such as rotation, scaling, and some cropping. It won't, of course, resist heavy modification of the image or heavy recoloring (and even a simple hue shift will be somewhat tricky).
http://en.wikipedia.org/wiki/RGB_color_space
http://upvector.com/index.php?section=tutorials&subsection=tutorials/colorspace
Another example involves something called the Hough Transform. This transform essentially decomposes an image into a set of lines. You can then take some of the 'strongest' lines in each image and see if they line up. You can do some extra work to try and compensate for rotation and scaling too -- and in this case, since comparing a few lines is MUCH less computational work than doing the same to entire images -- it won't be so bad.
http://homepages.inf.ed.ac.uk/amos/hough.html
http://rkb.home.cern.ch/rkb/AN16pp/node122.html
http://en.wikipedia.org/wiki/Hough_transform
An even shorter version:
require 'open-uri'
download = open('http://example.com/image.png')
IO.copy_stream(download, '~/image.png')
To keep the same filename:
IO.copy_stream(download, "~/#{download.base_uri.to_s.split('/')[-1]}")
As well as Amateras you could try Web Tools Project or Aptana. Although they will both give you way more than just a jsp editor.
Edit 2010/10/26 (comment from Simon Gibbs):
The Web Tools Project JSP editor is in the "Web Page Editor (Optional)" project.
Edit 2016/08/16 (extended comment from Dan Carter):
From Kepler (Eclipse 4.3.x) on, this is called "JSF Tools - Web Page Editor".
there are many options that would change the height of an input box. padding, font-size, height would all do this. different combinations of these produce taller input boxes with different styles. I suggest just changing the font-size (and font-family for looks) and add some padding to make it even taller and also more appealing. I will give you an example of all three style though:
#signin input {
font-size:20px;
}
OR
#signin input {
padding:10px;
}
OR
#signin input {
height:24px;
}
This is the combination of the three that I recommend:
#signin input {
font-size:20px;font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; font-weight: 300;
padding:10px;
}
This code works for fragments:
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
you pass the context to class B in it's constructor, and make sure you pass getApplicationContext() instead of a activityContext()
The principles behind this in computer science is called
? extends MyClass
,? super MyClass
andMyClass
The picture below should explain the concept. Picture courtesy: Andrey Tyukin
Another thing that people may find useful when using the develop
method is the --user
option to install without sudo. Ex:
python setup.py develop --user
instead of
sudo python setup.py develop
BundleConfig
is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)
To add this file, first you need to add the Microsoft.AspNet.Web.Optimization
nuget package to your web project:
Install-Package Microsoft.AspNet.Web.Optimization
Then under the App_Start folder create a new cs file called BundleConfig.cs
. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):
using System.Web;
using System.Web.Optimization;
namespace CodeRepository.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
Then modify your Global.asax and add a call to RegisterBundles()
in Application_Start()
:
using System.Web.Optimization;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app
In MySQL
set foreign_key_checks=0;
UPDATE patient INNER JOIN patient_address
ON patient.id_no=patient_address.id_no
SET patient.id_no='8008255601088',
patient_address.id_no=patient.id_no
WHERE patient.id_no='7008255601088';
Note that foreign_key_checks only temporarily set foreign key checking false. So it need to execute every time before update statement. We set it 0 as if we update parent first then that will not be allowed as child may have already that value. And if we update child first then that will also be not allowed as parent may not have that value from which we are updating. So we need to set foreign key check. Another thing is that if you are using command line tool to use this query then put care to mention spaces in place where i put new line or ENTER in code. As command line take it in one line, so it may happen that two words stick as patient_addressON which create syntax error.
Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf
between host and guest (there is known performance issues if there are large numbers of files/directories).
/vagrant
in guestVagrant is mounting the current working directory (where Vagrantfile
resides) as /vagrant
in the guest, this is the default behaviour.
See docs
NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.
You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true
in your Vagrantfile
.
Based on the output /tmp
on host was NOT mounted during up time.
Use VAGRANT_INFO=debug vagrant up
or VAGRANT_INFO=debug vagrant reload
to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp
on host should be drwxrwxrwt
).
I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)
config.vm.synced_folder "/tmp", "/tmp/src"
output
$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src
Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw)
.
Here is code to get line number and column position
function getLineNumber(tArea) {
return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}
function getCursorPos() {
var me = $("textarea[name='documenttext']")[0];
var el = $(me).get(0);
var pos = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
var ret = pos - prevLine(me);
alert(ret);
return ret;
}
function prevLine(me) {
var lineArr = me.value.substr(0, me.selectionStart).split("\n");
var numChars = 0;
for (var i = 0; i < lineArr.length-1; i++) {
numChars += lineArr[i].length+1;
}
return numChars;
}
tArea is the text area DOM element
I have found another way:
Tested on Firefox but it should work in other browsers too
Finally find out the problem:
the port 443 was listening on HTTP instead of HTTPS, changed to HTTPS solved my issue.
There are method join
for string objects:
".".join(("a","b","c"))
The syntax to modify a column in an existing table in SQL Server (Transact-SQL) is:
ALTER TABLE table_name
ALTER COLUMN column_name column_type;
For example:
ALTER TABLE employees
ALTER COLUMN last_name VARCHAR(75) NOT NULL;
This SQL Server ALTER TABLE
example will modify the column called last_name
to be a data type of VARCHAR(75)
and force the column to not allow null values.
see here
Since I just lost two days of my life trying to solve for tryCatch for an irr function, I thought I should share my wisdom (and what is missing). FYI - irr is an actual function from FinCal in this case where got errors in a few cases on a large data set.
Set up tryCatch as part of a function. For example:
irr2 <- function (x) {
out <- tryCatch(irr(x), error = function(e) NULL)
return(out)
}
For the error (or warning) to work, you actually need to create a function. I originally for error part just wrote error = return(NULL)
and ALL values came back null.
Remember to create a sub-output (like my "out") and to return(out)
.
Those two commands will create a ~/.vim/vim-haml/
directory with the ftplugin, syntax, etc directories in it. Those directories need to be immediately in the ~/.vim
directory proper or ~/.vim/vim-haml
needs to be added to the list of paths that vim searches for plugins.
Edit:
I recently decided to tweak my vim config and in the process wound up writing the following rakefile. It only works on Mac/Linux, but the advantage over cp
versions is that it's completely safe (symlinks don't overwrite existing files, uninstall only deletes symlinks) and easy to keep things updated.
# Easily install vim plugins from a source control checkout (e.g. Github)
#
# alias vim-install=rake -f ~/.vim/rakefile-vim-install
# vim-install
# vim-install uninstall
require 'ftools'
require 'fileutils'
task :default => :install
desc "Install a vim plugin the lazy way"
task :install do
vim_dir = File.expand_path("~/.vim")
plugin_dir = Dir.pwd
if not (FileTest.exists? File.join(plugin_dir,".git") or
FileTest.exists? File.join(plugin_dir,".svn") or
FileTest.exists? File.join(plugin_dir,".hg"))
puts "#{plugin_dir} isn't a source controlled directory. Aborting."
exit 1
end
Dir['**/'].each do |d|
FileUtils.mkdir_p File.join(vim_dir, d)
end
Dir["**/*.{txt,snippet,snippets,vim,js,wsf}"].each do |f|
ln File.join(plugin_dir, f), File.join(vim_dir,f)
end
boldred = "\033[1;31m"
clear = "\033[0m"
puts "\nDone. Remember to #{boldred}:helptags ~/.vim/doc#{clear}"
end
task :uninstall do
vim_dir = File.expand_path("~/.vim")
plugin_dir = Dir.pwd
Dir["**/*.{txt,snippet,snippets,vim}"].each do |f|
safe_rm File.join(vim_dir, f)
end
end
def nicename(path)
boldgreen = "\033[1;32m"
clear = "\033[0m"
return "#{boldgreen}#{File.join(path.split('/')[-2..-1])}#{clear}\t"
end
def ln(src, dst)
begin
FileUtils.ln_s src, dst
puts " Symlink #{nicename src}\t => #{nicename dst}"
rescue Errno::EEXIST
puts " #{nicename dst} exists! Skipping."
end
end
def cp(src, dst)
puts " Copying #{nicename src}\t=> #{nicename dst}"
FileUtils.cp src, dst
end
def safe_rm(target)
if FileTest.exists? target and FileTest.symlink? target
puts " #{nicename target} removed."
File.delete target
else
puts " #{nicename target} is not a symlink. Skipping"
end
end
I know this is a year old, but I just discovered this works perfectly for an EditText.
EditText textin = (EditText) findViewById(R.id.editText1);
textin.setInputType(InputType.TYPE_CLASS_TEXT);
It prevents anything but text and space. I could not tab, "return" ("\n"), or anything.
Use a RegExp:
if (!/ral/i.test(referrer)) {
...
}
Or, use .toLowerCase()
:
if (referrer.toLowerCase().indexOf("ral") == -1)
ArrayList newArrayList = (ArrayList) oldArrayList.clone();
This works for me:
filename = "foo"
text = File.read(filename)
content = text.gsub(/search_regexp/, "replacestring")
File.open(filename, "w") { |file| file << content }
It happens because your maven plugin try to connect to an HTTPS remote repository (https://repo.maven.apache.org/maven2) or (https://repo1.maven.apache.org).
Some time ago, you could to change these URL's to use HTTP instead use HTTPS, but since January 15th 2020, these URL's doesn't work any more, only the HTTPS URL's.
As an easy way to fix this problem, you can use the insecure Maven URL in the settings.xml file. So, you need to change ALL of yours references above mencioned to: http://insecure.repo1.maven.org/maven2/
TIP: Your JAVA_HOME variable always needs to point to your JDK path, not to your JRE path, for example: "C:\Program Files\Java\jdk1.7.0_80".
I had the same problem, and I solved it by doing:
After that, it should work.
When you install the android studio just by downloading from https://developer.android.com/studio/install.html sometimes sdk folder will not get appear in C:\Users\home\AppData\Local\Android Location..
But to set the android studio we need to set the path for android on this location.
So simply
1) start the android setup.
2) follow the instruction and android studio will automatically download the sdk folder by itself. (it will show the window like "Downloading Components").
After completing that installation check the above path again.
sdk folder will get appear now.
Yours:
<div style="height:42px;width:42px">
<img src="http://someimage.jpg">
Is it okay to use this code?
<div class= "box">
<img src= "http://someimage.jpg" class= "img">
</div>
<style type="text/css">
.box{width: 42; height: 42;}
.img{width: 20; height:20;}
</style>
Just trying, though late. :3 For someone else reading this, letme know if the way i wrote the code were not good. im new in this kind of language. and i still want to learn more.
It seems, that the simple way
-Dmaven.javadoc.skip=true
does not work with the release-plugin. in this case you have to pass the parameter as an "argument"
mvn release:perform -Darguments="-Dmaven.javadoc.skip=true"
I added it for all fieldsets with
fieldset {
border: 1px solid lightgray;
}
I didnt work if I set it separately using for example
border-color : red
. Then a black line was drawn next to the red line.
In Rails you can do this using underscore
method:
"Book Author Title".delete(' ').underscore.to_sym
=> :book_author_title
The simpler code is using regex (works with Ruby):
"Book Author Title".downcase.gsub(/\s+/, "_").to_sym
=> :book_author_title
A couple things
(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.
(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:
.button:after {
content: "";
width: 30px;
height: 30px;
background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
top: 10px;
right: 5px;
position: absolute;
display: inline-block;
}
I updated your jsFiddle to this and it showed the image.
Look at JavaDoc of replaceAll method of String class:
Replaces each substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression
java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)
As you can see you can use Pattern and Matcher to do that.
This worked for me
In JSP, to view the image
<img src="${pageContext.request.contextPath}/resources/images/slide-are.jpg">
In dispatcher-servlet.xml
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
Ubuntu these days comes with ufw - Uncomplicated Firewall. ufw is an easy-to-use method of handling iptables rules.
Try using this command to allow a port
sudo ufw allow 1701
To test connectivity, you could try shutting down the VPN software (freeing up the ports) and using netcat to listen, like this:
nc -l 1701
Then use telnet from your Windows host and see what shows up on your Ubuntu terminal. This can be repeated for each port you'd like to test.
<div class="headerdivider"></div>
and
.headerdivider {
border-left: 1px solid #38546d;
background: #16222c;
width: 1px;
height: 80px;
position: absolute;
right: 250px;
top: 10px;
}
ecatmur's solution will work fine. This will be better performance on large datasets, though:
data.groupby(data['date'].map(lambda x: x.year))
...and don't forget what happens when you mix types:
x = 127;
x += " hours "
// x is now a string: "127 hours "
x += 1 === 0;
// x is still a string: "127 hours false"
First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.
And other aspect is providing proper result. So you want to truncate the number or round it.
So before you start you should ask your self, am i interested on the value or not.
To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.
Go to My Computer>Properties>Advance System Settings>Environment Variables>
Under the variables of Administrator edit the PATH variable & change its value to "C:\Users\Username\AppData\Roaming\npm"
. Note: The username in the path will be the current Admin user's name that you have logged in with.
One way to avoid pass-by-reference errors (eg. "end(array_values($foo))") is to use call_user_func or call_user_func_array:
// PHP Fatal error: Only variables can be passed by reference
// No output (500 server error)
var_dump(end(array(1, 2, 3)));
// No errors, but modifies the array's internal pointer
// Outputs "int(3)"
var_dump(call_user_func('end', array(1, 2, 3)));
// PHP Strict standards: Only variables should be passed by reference
// Outputs "int(3)"
var_dump(end(array_values(array(1, 2, 3))));
// No errors, doesn't change the array
// Outputs "int(3)"
var_dump(call_user_func('end', array_values(array(1, 2, 3))));
Perhaps you should check NLS_DATE_FORMAT
and use the date string conforming the format.
Or you can use to_date
function within the INSERT
statement, like the following:
insert into visit
values(123456,
to_date('19-JUN-13', 'dd-mon-yy'),
to_date('13-AUG-13 12:56 A.M.', 'dd-mon-yyyy hh:mi A.M.'));
Additionally, Oracle DATE
stores date and time information together.
Here is how the standard keyboard behaves for each of these input types.
See this answer for more details.
Short answer in bolds:
collect
is mainly to serialize
(loss of parallelism preserving all other data characteristics of the dataframe)
For example with a PrintWriter pw
you can't do direct df.foreach( r => pw.write(r) )
, must to use collect
before foreach
, df.collect.foreach(etc)
.
PS: the "loss of parallelism" is not a "total loss" because after serialization it can be distributed again to executors.
select
is mainly to select columns, similar to projection in relational algebra
(only similar in framework's context because Spark select
not deduplicate data).
So, it is also a complement of filter
in the framework's context.
Commenting explanations of other answers: I like the Jeff's classification of Spark operations in transformations (as select
) and actions (as collect
). It is also good remember that transforms (including select
) are lazily evaluated.
Also lazy
is useful without cyclic dependencies, as in the following code:
abstract class X {
val x: String
println ("x is "+x.length)
}
object Y extends X { val x = "Hello" }
Y
Accessing Y
will now throw null pointer exception, because x
is not yet initialized.
The following, however, works fine:
abstract class X {
val x: String
println ("x is "+x.length)
}
object Y extends X { lazy val x = "Hello" }
Y
EDIT: the following will also work:
object Y extends { val x = "Hello" } with X
This is called an "early initializer". See this SO question for more details.
--
-- SQL DATEDIFF getting midnight time parts
--
SELECT GETDATE() AS Now,
Convert(DateTime, DATEDIFF(DAY, 0, GETDATE())) AS MidnightToday,
Convert(DateTime, DATEDIFF(DAY, -1, GETDATE())) AS MidnightNextDay,
Convert(DateTime, DATEDIFF(DAY, 1, GETDATE())) AS MidnightYesterDay
go
Now MidnightToday MidnightNextDay MidnightYesterDay
-------------------- --------------------- --------------------- ---------------------
8/27/2014 4:30:22 PM 8/27/2014 12:00:00 AM 8/28/2014 12:00:00 AM 8/26/2014 12:00:00 AM
This is most likely because you have multiple accounts, like one private, one for work with GitHub.
SOLUTION On Windows, go to Start > Credential Manager > Windows Credentials and remove GitHub creds, then try pulling or pushing again and you will be prompted to relogin into GitHub
SOLUTION OnMac, issue following on terminal:
git remote set-url origin https://[email protected]/username/repo-name.git
by replacing 'username' with your GitHub username in both places and providing your GitHub repo name.
Updated
For MS SQL Server 2012 and above
USE [master];
DECLARE @kill varchar(8000) = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';'
FROM sys.dm_exec_sessions
WHERE database_id = db_id('MyDB')
EXEC(@kill);
For MS SQL Server 2000, 2005, 2008
USE master;
DECLARE @kill varchar(8000); SET @kill = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'
FROM master..sysprocesses
WHERE dbid = db_id('MyDB')
EXEC(@kill);
For me the thing that worked was the order in which the namespaces were defined in the xsi:schemaLocation tag : [ since the version was all good and also it was transaction-manager already ]
The error was with :
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
AND RESOLVED WITH :
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document
) and will be executed when an event reaches that element having originated on an element matching the selector.
This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id
element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.
The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.
By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id
element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.
Give this a go:
string format = "{0} / {1} / {2} {3}";
string date = string.Format(format,mon.ToString(),da.ToString(),yer.ToString();
Console.WriteLine(date);
In fact, there's probably a way to format it automatically without even doing it yourself.
Check out http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
If your string contains exactly one character the simplest way to convert it to a character is probably to call the charAt
method:
char c = s.charAt(0);
Simple Try to make a function in javascript for dropdown collapse class.
Example:
JS:
$scope.toogleMyClass = function(){
//dropdown-element
$timeout(function(){
$scope.preLoader = false;
$(document).ready(function() {
$("#dropdown-element").toggleClass('show');
});
},100);
};
Hook this function to onClick
simple works for me.
In the first example, ptr has not been initialized, so it points to an unspecified memory location. When you assign something to this unspecified location, your program blows up.
In the second example, the address is set when you say ptr = &q, so you're OK.
List<Book> books_2 = new List<Book>(books_2.ToArray());
That should do exactly what you want. Demonstrated here.
Just a tip: Remember to put the code detection on document.ready, otherwise it might not work. That was my case.
I added a HorizontalAlignment="Center" (The default is "Strech") and it solved my problem because it made the datagrid only as wide as needed. (Removed the datagrid's Width setting if you have one.)
Chkconfig is no longer available in Ubuntu.
Chkconfig is a script. You can download it from here.
This is what I used in a project, parses a single line of data.
private string[] csvParser(string csv, char separator = ',')
{
List <string> = new <string>();
string[] temp = csv.Split(separator);
int counter = 0;
string data = string.Empty;
while (counter < temp.Length)
{
data = temp[counter].Trim();
if (data.Trim().StartsWith("\""))
{
bool isLast = false;
while (!isLast && counter < temp.Length)
{
data += separator.ToString() + temp[counter + 1];
counter++;
isLast = (temp[counter].Trim().EndsWith("\""));
}
}
parsed.Add(data);
counter++;
}
return parsed.ToArray();
}
http://zamirsblog.blogspot.com/2013/09/c-csv-parser-csvparser.html
You can use the isnan()
function, but you need to include the C math library.
#include <cmath>
As this function is part of C99, it is not available everywhere. If your vendor does not supply the function, you can also define your own variant for compatibility.
inline bool isnan(double x) {
return x != x;
}
I do not believe there is a "per query" way to do this. (You can use the use
keyword to specify the database - not the schema - but that's technically a separate query as you have to issue the go
command afterward.)
Remember, in SQL server fully qualified table names are in the format:
[database].[schema].[table]
In SQL Server Management Studio you can configure all the defaults you're asking about.
You can set up the default database
on a per-user basis (or in your connection string):
Security > Logins > (right click) user > Properties > General
You can set up the default schema
on a per-user basis (but I do not believe you can configure it in your connection string, although if you use dbo
that is always the default):
Security > Logins > (right click) user > Properties > User Mapping > Default Schema
In short, if you use dbo
for your schema, you'll likely have the least amount of headaches.
add this line end of php.ini
openssl.cafile=/opt/lampp/share/curl/curl-ca-bundle.crt
may be curl path cannot be identified by PHP
I do know that the account needs to have "Log on as a Service" privileges. Other than that, I'm not sure. A quick reference to Log on as a Service can be found here, and there is a lot of information of specific privileges here.
For anyone who wants to sort the variable in third layer:
<select ng-option="friend.pet.name for friend in friends"></select>
you can do it like this
<select ng-option="friend.pet.name for friend in friends | orderBy: 'pet.name'"></select>
You can use for loop if you really want to.
char table[][] table = new char[row][col];
for(int i = 0; i < row * col ; ++i){
table[i/row][i % col] = char('a' + (i+1));
}
or do what bhesh said.
Correct ways in jQuery are -
$('#test').prop('scrollHeight')
OR$('#test')[0].scrollHeight
OR$('#test').get(0).scrollHeight
You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of
function email() {
// Opens SS by its ID
var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");
// Get the name of this SS
var name = ss.getName(); // Not necessary
// Read cell 1,1 * Line below does't work *
// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();
}
The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.
// Checking the format
var urlString: NSString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
// Convert your data and set your request's HTTPBody property
var stringData: NSString = NSString(string: "jsonRequest=\(urlString)")
var requestBodyData: NSData = stringData.dataUsingEncoding(NSUTF8StringEncoding)!
InetAddress.isReachable
sometime return false if internet connection exist.
An alternative method to check internet availability in java is : This function make a real ICMP ECHO
ping.
public static boolean isReachableByPing(String host) {
try{
String cmd = "";
if(System.getProperty("os.name").startsWith("Windows")) {
// For Windows
cmd = "ping -n 1 " + host;
} else {
// For Linux and OSX
cmd = "ping -c 1 " + host;
}
Process myProcess = Runtime.getRuntime().exec(cmd);
myProcess.waitFor();
if(myProcess.exitValue() == 0) {
return true;
} else {
return false;
}
} catch( Exception e ) {
e.printStackTrace();
return false;
}
}
Encountered a similar problem after upgrading to Catalina OS. After running mysqld command, I found that there was some issue with the logs file. It could be different for others.
$ mysqld
Issue was
2019-10-16T04:58:59.174474Z 0 [ERROR] Could not open file '/var/log/mysql/error.log' for error logging: No such file or directory
2019-10-16T04:58:59.174508Z 0 [ERROR] Aborting
Resolved it by creating it and applying proper permissions.
sudo mkdir -p /var/log/mysql
sudo touch /var/log/mysql/error.log
sudo chown -R _mysql:mysql /var/log/mysql/
Restart MySQL
brew services restart [email protected]
Issue was resolved.
mysql -uroot -proot
Sorry: There is a mistake in my code before because of the site validation.
String myFile = "/Name Folder/File.jpg";
String myPath = Environment.getExternalStorageDirectory()+myFile;
File f = new File(myPath);
Boolean deleted = f.delete();
I think is clear...
First you must to know your file location.
Second,,, Environment.getExternalStorageDirectory()
is a method who gets your app directory.
Lastly the class File who handle your file...
The simplest way of doing this would be to add
include_directories(${CMAKE_SOURCE_DIR}/inc)
link_directories(${CMAKE_SOURCE_DIR}/lib)
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib
The modern CMake version that doesn't add the -I and -L
flags to every compiler invocation would be to use imported libraries:
add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
set_target_properties(bar PROPERTIES
IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
)
set(FOO_SRCS "foo.cpp")
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # also adds the required include path
If setting the INTERFACE_INCLUDE_DIRECTORIES
doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include)
. However, this no longer works with CMake 3.6 or newer.
Are you building this string using single or double quotes? \r and \n only work with double quotes, as well as embedded variables. For example:
$foo = 'bar';
echo 'Hello \n $foo!';
will output:
Hello \n $foo!
But:
$foo = 'bar';
echo "Hello \n $foo!";
will output:
Hello
bar!
AJAX is the best way to do asynchronous tasks. Making asynchronous calls is something common in use in any website building. We will take a short example to learn how we can implement AJAX in Django. We need to use jQuery so as to write less javascript.
This is Contact example, which is the simplest example, I am using to explain the basics of AJAX and its implementation in Django. We will be making POST request in this example. I am following one of the example of this post: https://djangopy.org/learn/step-up-guide-to-implement-ajax-in-django
models.py
Let's first create the model of Contact, having basic details.
from django.db import models
class Contact(models.Model):
name = models.CharField(max_length = 100)
email = models.EmailField()
message = models.TextField()
timestamp = models.DateTimeField(auto_now_add = True)
def __str__(self):
return self.name
forms.py
Create the form for the above model.
from django import forms
from .models import Contact
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
exclude = ["timestamp", ]
views.py
The views look similar to the basic function-based create view, but instead of returning with render, we are using JsonResponse response.
from django.http import JsonResponse
from .forms import ContactForm
def postContact(request):
if request.method == "POST" and request.is_ajax():
form = ContactForm(request.POST)
form.save()
return JsonResponse({"success":True}, status=200)
return JsonResponse({"success":False}, status=400)
urls.py
Let's create the route of the above view.
from django.contrib import admin
from django.urls import path
from app_1 import views as app1
urlpatterns = [
path('ajax/contact', app1.postContact, name ='contact_submit'),
]
template
Moving to frontend section, render the form which was created above enclosing form tag along with csrf_token and submit button. Note that we have included the jquery library.
<form id = "contactForm" method= "POST">{% csrf_token %}
{{ contactForm.as_p }}
<input type="submit" name="contact-submit" class="btn btn-primary" />
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Javascript
Let's now talk about javascript part, on the form submit we are making ajax request of type POST, taking the form data and sending to the server side.
$("#contactForm").submit(function(e){
// prevent from normal form behaviour
e.preventDefault();
// serialize the form data
var serializedData = $(this).serialize();
$.ajax({
type : 'POST',
url : "{% url 'contact_submit' %}",
data : serializedData,
success : function(response){
//reset the form after successful submit
$("#contactForm")[0].reset();
},
error : function(response){
console.log(response)
}
});
});
This is just a basic example to get started with AJAX with django, if you want to get dive with several more examples, you can go through this article: https://djangopy.org/learn/step-up-guide-to-implement-ajax-in-django
PEP 8 advises the first form for readability. You can find it here.
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Could always do:
db.foo.find().forEach(function(f){print(tojson(f, '', true));});
To get that compact view.
Also, I find it very useful to limit the fields returned by the find so:
db.foo.find({},{name:1}).forEach(function(f){print(tojson(f, '', true));});
which would return only the _id and name field from foo.
Not only double quotes, you will be in need for single quote ('
), double quote ("
), backslash (\
) and NUL (the NULL byte).
Use fputcsv()
to write, and fgetcsv()
to read, which will take care of all.
Which method is used to check if SESSION exists or not? Answer:
isset($_SESSION['variable_name'])
Example:
isset($_SESSION['id'])
The usernames are shown in the dba_users's username
column, there is a script you can run called:
alter user username identified by password
You can get more information here - https://community.oracle.com/thread/632617?tstart=0
package article14;
import java.io.File;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.util.PDFMergerUtility;
public class Pdf
{
public static void main(String args[])
{
new Pdf().createNew();
new Pdf().combine();
}
public void combine()
{
try
{
PDFMergerUtility mergePdf = new PDFMergerUtility();
String folder ="pdf";
File _folder = new File(folder);
File[] filesInFolder;
filesInFolder = _folder.listFiles();
for (File string : filesInFolder)
{
mergePdf.addSource(string);
}
mergePdf.setDestinationFileName("Combined.pdf");
mergePdf.mergeDocuments();
}
catch(Exception e)
{
}
}
public void createNew()
{
PDDocument document = null;
try
{
String filename="test.pdf";
document=new PDDocument();
PDPage blankPage = new PDPage();
document.addPage( blankPage );
document.save( filename );
}
catch(Exception e)
{
}
}
}
I had this problem when I try to write a very long url, the following works.
image_url = %w(
http://minio.127.0.0.1.xip.io:9000/
bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
28ed3774-b234-4de2-9a11-7d657707f79c?
X-Amz-Algorithm=AWS4-HMAC-SHA256&
X-Amz-Credential=ABABABABABABABABA
%2Fus-east-1%2Fs3%2Faws4_request&
X-Amz-Date=20170702T000940Z&
X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
X-Amz-Signature=ABABABABABABABABABABAB
ABABABABABABABABABABABABABABABABABABA
).join
Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.
Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.
How about an approach that not only allows multiple domains, but allows dynamic domains.
The use case here is with a Sharepoint app part which loads our site inside of Sharepoint via an iframe. The problem is that sharepoint has dynamic subdomains such as https://yoursite.sharepoint.com. So for IE, we need to specify ALLOW-FROM https://.sharepoint.com
Tricky business, but we can get it done knowing two facts:
When an iframe loads, it only validates the X-Frame-Options on the first request. Once the iframe is loaded, you can navigate within the iframe and the header isn't checked on subsequent requests.
Also, when an iframe is loaded, the HTTP referer is the parent iframe url.
You can leverage these two facts server side. In ruby, I'm using the following code:
uri = URI.parse(request.referer)
if uri.host.match(/\.sharepoint\.com$/)
url = "https://#{uri.host}"
response.headers['X-Frame-Options'] = "ALLOW-FROM #{url}"
end
Here we can dynamically allow domains based upon the parent domain. In this case, we ensure that the host ends in sharepoint.com keeping our site safe from clickjacking.
I'd love to hear feedback on this approach.
Firstly you need to install a SSH server in the images you wish to ssh-into. You can use a base image for all your container with the ssh server installed.
Then you only have to run each container mapping the ssh port (default 22) to one to the host's ports (Remote Server in your image), using -p <hostPort>:<containerPort>
. i.e:
docker run -p 52022:22 container1
docker run -p 53022:22 container2
Then, if ports 52022 and 53022 of host's are accessible from outside, you can directly ssh to the containers using the ip of the host (Remote Server) specifying the port in ssh with -p <port>
. I.e.:
ssh -p 52022 myuser@RemoteServer
--> SSH to container1
ssh -p 53022 myuser@RemoteServer
--> SSH to container2
Using "fill" attribute helps in cases like this. You can remove the text from axis using element_blank()
and show multi color bar chart with a legend. I am plotting a part removal frequency in a repair shop as below
ggplot(data=df_subset,aes(x=Part,y=Removal_Frequency,fill=Part))+geom_bar(stat="identity")+theme(axis.text.x = element_blank())
I went for this solution in my case as I had many bars in bar chart and I was not able to find a suitable font size which is both readable and also small enough not to overlap each other.
In SQL Management Studio, go to Security -> Logins and double click your Login. Choose Server Roles from the left column, and verify that sysadmin is checked.
In my case, I was logged in on an account without that privilege.
HTH!
It would be better to just fetch the data into array like this:
<?php
$shop = array( array("title"=>"rose", "price"=>1.25 , "number"=>15),
array("title"=>"daisy", "price"=>0.75 , "number"=>25),
array("title"=>"orchid", "price"=>1.15 , "number"=>7)
);
?>
And then do something like this, which should work well even when you add more columns to your table in the database later.
<?php if (count($shop) > 0): ?>
<table>
<thead>
<tr>
<th><?php echo implode('</th><th>', array_keys(current($shop))); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($shop as $row): array_map('htmlentities', $row); ?>
<tr>
<td><?php echo implode('</td><td>', $row); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
You can find the last commit which deleted file as follows:
git rev-list -n 1 HEAD -- [file_path]
Further information is available here
You can do it as following, which is the shortest way.
$results = User::where(['this'=>1, 'that'=>1, 'this_too'=>1, 'that_too'=>1,
'this_as_well'=>1, 'that_as_well'=>1, 'this_one_too'=>1, 'that_one_too'=>1,
'this_one_as_well'=>1, 'that_one_as_well'=>1])->get();
You can also perform Implicit Type Conversions with template literals. Example:
let fruits = ["mango","orange","pineapple","papaya"];
console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya
To get the fragment instance in a class that extends FragmentActivity:
MyclassFragment instanceFragment=
(MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);
To get the fragment instance in a class that extends Fragment:
MyclassFragment instanceFragment =
(MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);
The SweetAlert repo seems to be unmaintained. There's a bunch of Pull Requests without any replies, the last merged pull request was on Nov 9, 2014.
I created SweetAlert2 with HTML support in modal and some other options for customization modal window - width, padding, Esc button behavior, etc.
Swal.fire({
title: "<i>Title</i>",
html: "Testno sporocilo za objekt: <b>test</b>",
confirmButtonText: "V <u>redu</u>",
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
_x000D_
You can use the rotate attribute
<item>
<rotate
android:fromDegrees="90"
android:toDegrees="90"
android:pivotX="50%"
android:pivotY="50%" >
<shape
android:shape="line"
android:top="1dip" >
<stroke
android:width="1dip"
/>
</shape>
</rotate>
</item>
What about 208 - http://httpstatusdogs.com/208-already-reported ? Is that a option?
In my opinion, if the only thing is a repeat resource no error should be raised. After all, there is no error neither on the client or server sides.
In short: You should be able to achieve in the order of millions of simultaneous active TCP connections and by extension HTTP request(s). This tells you the maximum performance you can expect with the right platform with the right configuration.
Today, I was worried whether IIS with ASP.NET would support in the order of 100 concurrent connections (look at my update, expect ~10k responses per second on older ASP.Net Mono versions). When I saw this question/answers, I couldn't resist answering myself, many answers to the question here are completely incorrect.
Best Case
The answer to this question must only concern itself with the simplest server configuration to decouple from the countless variables and configurations possible downstream.
So consider the following scenario for my answer:
Detailed Answer
Synchronous thread-bound designs tend to be the worst performing relative to Asynchronous IO implementations.
WhatsApp can handle a million WITH traffic on a single Unix flavoured OS machine - https://blog.whatsapp.com/index.php/2012/01/1-million-is-so-2011/.
And finally, this one, http://highscalability.com/blog/2013/5/13/the-secret-to-10-million-concurrent-connections-the-kernel-i.html, goes into a lot of detail, exploring how even 10 million could be achieved. Servers often have hardware TCP offload engines, ASICs designed for this specific role more efficiently than a general purpose CPU.
Good software design choices
Asynchronous IO design will differ across Operating Systems and Programming platforms. Node.js was designed with asynchronous in mind. You should use Promises at least, and when ECMAScript 7 comes along, async
/await
. C#/.Net already has full asynchronous support like node.js. Whatever the OS and platform, asynchronous should be expected to perform very well. And whatever language you choose, look for the keyword "asynchronous", most modern languages will have some support, even if it's an add-on of some sort.
To WebFarm?
Whatever the limit is for your particular situation, yes a web-farm is one good solution to scaling. There are many architectures for achieving this. One is using a load balancer (hosting providers can offer these, but even these have a limit, along with bandwidth ceiling), but I don't favour this option. For Single Page Applications with long-running connections, I prefer to instead have an open list of servers which the client application will choose from randomly at startup and reuse over the lifetime of the application. This removes the single point of failure (load balancer) and enables scaling through multiple data centres and therefore much more bandwidth.
Busting a myth - 64K ports
To address the question component regarding "64,000", this is a misconception. A server can connect to many more than 65535 clients. See https://networkengineering.stackexchange.com/questions/48283/is-a-tcp-server-limited-to-65535-clients/48284
By the way, Http.sys on Windows permits multiple applications to share the same server port under the HTTP URL schema. They each register a separate domain binding, but there is ultimately a single server application proxying the requests to the correct applications.
Update 2019-05-30
Here is an up to date comparison of the fastest HTTP libraries - https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=plaintext
SqlDependency doesn't watch the database it watches the SqlCommand you specify so if you are trying to lets say insert values into the database in 1 project and capture that event in another project it won't work because the event was from the SqlCommand from the 1º project not the database because when you create an SqlDependency you link it to a SqlCommand and only when that command from that project is used does it create a Change event.
Use -C
option of tar:
tar zxvf <yourfile>.tar.gz -C /usr/src/
and then, the content of the tar should be in:
/usr/src/<yourfile>
Use YouTube Android Player API.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.andreaskonstantakos.vfy.MainActivity">
<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:layout_centerHorizontal="true"
android:id="@+id/youtube_player"
android:layout_alignParentTop="true" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="195dp"
android:visibility="visible"
android:id="@+id/button" />
</RelativeLayout>
MainActivity.java:
package com.example.andreaskonstantakos.vfy;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends YouTubeBaseActivity {
YouTubePlayerView youTubePlayerView;
Button button;
YouTubePlayer.OnInitializedListener onInitializedListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
button = (Button) findViewById(R.id.button);
onInitializedListener = new YouTubePlayer.OnInitializedListener(){
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo("Hce74cEAAaE");
youTubePlayer.play();
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
youTubePlayerView.initialize(PlayerConfig.API_KEY,onInitializedListener);
}
});
}
}
and the PlayerConfig.java class:
package com.example.andreaskonstantakos.vfy;
/**
* Created by Andreas Konstantakos on 13/4/2017.
*/
public class PlayerConfig {
PlayerConfig(){}
public static final String API_KEY =
"xxxxx";
}
Replace the "Hce74cEAAaE" with your video ID from https://www.youtube.com/watch?v=Hce74cEAAaE. Get your API_KEY from Console.developers.google.com and also replace it on the PlayerConfig.API_KEY. For any further information you can follow the following tutorial step by step: https://www.youtube.com/watch?v=3LiubyYpEUk
GLib and gnulib
These are your likely best bets if you don't have more specific requirements, since they are widely available, portable and likely efficient.
GLib: https://developer.gnome.org/glib/ by GNOME project. Several containers documented at: https://developer.gnome.org/glib/stable/glib-data-types.html including "Hash Tables" and "Balanced Binary Trees". License: LGPL
gnulib: https://www.gnu.org/software/gnulib/ by the GNU project. You are meant to copy paste the source into your code. Several containers documented at: https://www.gnu.org/software/gnulib/MODULES.html#ansic_ext_container including "rbtree-list", "linkedhash-list" and "rbtreehash-list". GPL license.
See also: Are there any open source C libraries with common data structures?
A safe version to convert an iterator to a pointer (exactly what that means regardless of the implications) and by safe I mean no worries about having to dereference the iterator and cause possible exceptions / errors due to end()
/ other situations
#include <iostream>
#include <vector>
#include <string.h>
int main()
{
std::vector<int> vec;
char itPtr[25];
long long itPtrDec;
std::vector<int>::iterator it = vec.begin();
memset(&itPtr, 0, 25);
sprintf(itPtr, "%llu", it);
itPtrDec = atoll(itPtr);
printf("it = 0x%X\n", itPtrDec);
vec.push_back(123);
it = vec.begin();
memset(&itPtr, 0, 25);
sprintf(itPtr, "%llu", it);
itPtrDec = atoll(itPtr);
printf("it = 0x%X\n", itPtrDec);
}
will print something like
it = 0x0
it = 0x2202E10
It's an incredibly hacky way to do it, but if you need it, it does the job. You will receive some compiler warnings which, if really bothering you, can be removed with #pragma
You are better off using an iterator instead. Relevant: http://docs.python.org/library/fileinput.html
From the docs:
import fileinput
for line in fileinput.input("filename"):
process(line)
This will avoid copying the whole file into memory at once.
Sounds like an error you would get when your forms authentication ticket has expired. What is the timeout period for your ticket? Is it set to sliding or absolute expiration?
I believe the default for the timeout is 20 minutes with sliding expiration so if a user gets authenticated and at some point doesn't hit your site for 20 minutes their ticket would be expired. If it is set to absolute expiration it will expire X number of minutes after it was issued where X is your timeout setting.
You can set the timeout and expiration policy (e.g. sliding, absolute) in your web/machine.config
under /configuration/system.web/authentication/forms
I vote whoever can solve like me. I had this same problem as u , I spent many hours to get correct . Please test .
Upgrade entire SDK , the update 21.0.2 build also has updates from Google Services play . Upgrade everything. In your workspace delete folders ( android -support- v7 - AppCompat ) and ( google -play - services_lib )
Re-import these projects into the IDE and select to copy them to your workspace again.
The project ( google -play - services_lib ) to perform the action of Refresh and Build
**** ***** Problem The project ( android -support- v7 - AppCompat ) mark the 5.0 API then Refresh and Build .
In his project , in properties , android , import libraries ( android -support- v7 - AppCompat ) and ( google -play - services_lib ) then Refresh and Build .
The ISO file that suggested in the accepted answer is still not complete. The very complete offline installer is about 24GB! There is only one way to get it. follow these steps:
temp
folderC:\VS Community\
C:\VS
Community\
with this argument: /Layout .
Good Luck
order by -cast([Next_Contact_Date] as bigint) desc
You can insert arbitrary PowerShell script code in a double-quoted string by using a subexpression, for example, $() like so:
"C:\temp\mybackup $(get-date -f yyyy-MM-dd).zip"
And if you are getting the path from somewhere else - already as a string:
$dirName = [io.path]::GetDirectoryName($path)
$filename = [io.path]::GetFileNameWithoutExtension($path)
$ext = [io.path]::GetExtension($path)
$newPath = "$dirName\$filename $(get-date -f yyyy-MM-dd)$ext"
And if the path happens to be coming from the output of Get-ChildItem:
Get-ChildItem *.zip | Foreach {
"$($_.DirectoryName)\$($_.BaseName) $(get-date -f yyyy-MM-dd)$($_.extension)"}
var fileStream = fs.createWriteStream('/path/to/file.jpg');
var s3Stream = s3.getObject({Bucket: 'myBucket', Key: 'myImageFile.jpg'}).createReadStream();
// Listen for errors returned by the service
s3Stream.on('error', function(err) {
// NoSuchKey: The specified key does not exist
console.error(err);
});
s3Stream.pipe(fileStream).on('error', function(err) {
// capture any errors that occur when writing data to the file
console.error('File Stream:', err);
}).on('close', function() {
console.log('Done.');
});
Reference: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/requests-using-stream-objects.html
Alternative way with just one class while keeping your styles in a CSS file, which even works in IE7:
<table class="mytable">
<tr>
<th>From</th>
<th>Subject</th>
<th>Date</th>
</tr>
</table>
<style>
.mytable td, .mytable th { width:15%; }
.mytable td + td, .mytable th + th { width:70%; }
.mytable td + td + td, .mytable th + th + th { width:15%; }
</style>
More recently, you can also use the nth-child()
selector from CSS3 (IE9+), where you'd just put the nr. of the respective column into the parenthesis instead of stringing them together with the adjacent selector. Like this, for example:
<style>
.mytable tr > *:nth-child(1) { width:15%; }
.mytable tr > *:nth-child(2) { width:70%; }
.mytable tr > *:nth-child(3) { width:15%; }
</style>
It means a call to a virtual function will be forwarded to the "right" class.
C++ FAQ Lite FTW.
In short, it is often used in multiple-inheritance scenarios, where a "diamond" hierarchy is formed. Virtual inheritance will then break the ambiguity created in the bottom class, when you call function in that class and the function needs to be resolved to either class D1 or D2 above that bottom class. See the FAQ item for a diagram and details.
It is also used in sister delegation, a powerful feature (though not for the faint of heart). See this FAQ.
Also see Item 40 in Effective C++ 3rd edition (43 in 2nd edition).
I too had this problem. My solution was:
sc.setSoLinger(true, 10);
COPY FROM A WEBSITE -->By using the setSoLinger()
method, you can explicitly set a delay before a reset is sent, giving more time for data to be read or send.
Maybe it is not the answer to everybody but to some people.
You can deserialize directly to a list by using the TypeReference
wrapper. An example method:
public static <T> T fromJSON(final TypeReference<T> type,
final String jsonPacket) {
T data = null;
try {
data = new ObjectMapper().readValue(jsonPacket, type);
} catch (Exception e) {
// Handle the problem
}
return data;
}
And is used thus:
final String json = "";
Set<POJO> properties = fromJSON(new TypeReference<Set<POJO>>() {}, json);
When you run the Windows Command Prompt, and type in python
, it starts the Python interpreter.
Typing it again tries to interpret python
as a variable, which doesn't exist and thus won't work:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line
C:\Users\USER>
If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python
is interpreted as a variable, which you have not defined.
I encountered the same error when added http-builder to dependencies.
In my case, I could solve by simply excluding asm like this:
compile('org.codehaus.groovy.modules.http-builder:http-builder:0.7'){
excludes 'xml-apis'
exclude(group:'xerces', module: 'xercesImpl')
excludes 'asm'
}
Another option, if you need to sign the executable on a Linux box is to use signcode from the Mono project tools. It is supported on Ubuntu.
You would have to configure your webserver to utilize PHP as handler for .html
files. This is typically done by modifying your with AddHandler
to include .html
along with .php
.
Note that this could have a performance impact as this would cause ALL .html files to be run through PHP handler even if there is no PHP involved. So you might strongly consider using .php
extension on these files and adding a redirect as necessary to route requests to specific .html URL's to their .php equivalents.
I used the answer of Steve Mallory, but I am affraid the timer never or at least sometimes does not go to 86400 nor 0 (zero) sharp (MS Access 2013). So I modified the code. I changed the midnight condition to "If Timer >= 86399 Then" and added the break of the loop "Exit Do" as follows:
Public Function Pause(NumberOfSeconds As Variant)
On Error GoTo Error_GoTo
Dim PauseTime As Variant
Dim Start As Variant
Dim Elapsed As Variant
PauseTime = NumberOfSeconds
Start = Timer
Elapsed = 0
Do While Timer < Start + PauseTime
Elapsed = Elapsed + 1
If Timer >= 86399
' Crossing midnight
' PauseTime = PauseTime - Elapsed
' Start = 0
' Elapsed = 0
Exit Do
End If
DoEvents
Loop
Exit_GoTo:
On Error GoTo 0
Exit Function
Error_GoTo:
Debug.Print Err.Number, Err.Description, Erl
GoTo Exit_GoTo
End Function
SELECT SUBSTR(TRIM(rtp.role),1,12) AS ROLE
, SUBSTR(rp.grantee,1,16) AS GRANTEE
, SUBSTR(TRIM(rtp.privilege),1,12) AS PRIVILEGE
, SUBSTR(TRIM(rtp.owner),1,12) AS OWNER
, SUBSTR(TRIM(rtp.table_name),1,28) AS TABLE_NAME
, SUBSTR(TRIM(rtp.column_name),1,20) AS COLUMN_NAME
, SUBSTR(rtp.common,1,4) AS COMMON
, SUBSTR(rtp.grantable,1,4) AS GRANTABLE
, SUBSTR(rp.default_role,1,16) AS DEFAULT_ROLE
, SUBSTR(rp.admin_option,1,4) AS ADMIN_OPTION
FROM role_tab_privs rtp
LEFT JOIN dba_role_privs rp
ON (rtp.role = rp.granted_role)
WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
ORDER BY 1
, 2
, 3
, 4
;
SQLPLUS> @all_roles '' '' '' '' '' ''
SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
etc.
replace()
method:From the urlStr
string:
paramVal = urlStr.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
or from the current URL:
paramVal = document.URL.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
Explanation:
document.URL
- interface returns the document location (page url) as a string.replace()
- method returns a new string with some or all matches of a pattern replaced by a replacement./.*param_name=([^&]*).*/
- the regular expression pattern enclosed between slashes which means:
.*
- zero or more of any characters,param_name=
- param name which is serched,()
- group in regular expression,[^&]*
- one or more of any characters excluding &
,|
- alternation,$1
- reference to first group in regular expression.var urlStr = 'www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5';_x000D_
var c = urlStr.replace(/.*c=([^&]*).*|(.*)/, '$1');_x000D_
var notExisted = urlStr.replace(/.*not_existed=([^&]*).*|(.*)/, '$1');_x000D_
console.log(`c === '${c}'`);_x000D_
console.log(`notExisted === '${notExisted}'`);
_x000D_
Oldest:
oldest = min(datetimes)
Youngest before now:
now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)
If you want the text value of a QString object you can use the __str__
property, like this:
>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'
Hope that helps.
Starting with Vue2, the triple braces were deprecated, you are to use v-html
.
<div v-html="task.html_content"> </div>
It is unclear from the documentation link as to what we are supposed to place inside v-html
, your variables goes inside v-html
.
Also, v-html
works only with <div>
or <span>
but not with <template>
.
If you want to see this live in an app, click here.
SQL Server functions, like cursors, are meant to be used as your last weapon! They do have performance issues and therefore using a table-valued function should be avoided as much as possible. Talking about performance is talking about a table with more than 1,000,000 records hosted on a server on a middle-class hardware; otherwise you don't need to worry about the performance hit caused by the functions.
for further reference see: http://databases.aspfaq.com/database/should-i-use-a-view-a-stored-procedure-or-a-user-defined-function.html
Anyone using JavaScript (as opposed to JQuery), might like to try this solution, where 'models' is the ID of the select field containing the list :-
var DDlist = document.getElementById("models");
while(DDlist.length>0){DDlist.remove(0);}
Assuming you're referring to this plugin, your code should be:
// To Store
$(function() {
$.session.set("myVar", "value");
});
// To Read
$(function() {
alert($.session.get("myVar"));
});
Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown
file, which is displayed on the project page.
I have done this and it has worked.
Properties props = PropertiesLoaderUtils.loadAllProperties("my.properties");
PropertyPlaceholderConfigurer props2 = new PropertyPlaceholderConfigurer();
props2.setProperties(props);
That should work.
It is possible to get the command line shell output of a process as described here : http://www.c-sharpcorner.com/UploadFile/edwinlima/SystemDiagnosticProcess12052005035444AM/SystemDiagnosticProcess.aspx
This depends on mencoder. If it ouputs this status on the command line then yes :)
Another way to do it would be to inspect the url bar in chrome to find the id of the element, have your WebDriver click that element, and then send the keys you use to copy and paste using the keys common function from selenium, and then printing it out or storing it as a variable, etc.
to modify more css property values, you may use css object. such as:
hilight_css = {"border-bottom-color":"red",
"background-color":"#000"};
$(".msg").css(hilight_css);
but if the modification code is bloated. you should consider the approach March suggested. do it this way:
first, in your css file:
.hilight { border-bottom-color:red; background-color:#000; }
.msg { /* something to make it notifiable */ }
second, in your js code:
$(".msg").addClass("hilight");
// to bring message block to normal
$(".hilight").removeClass("hilight");
if ie 6 is not an issue, you can chain these classes to have more specific selectors.
I will try to demonstrate Encapsulation in a simple way.. Lets see..
Encapsulation is -
Encapsulation implements Abstraction.
And Abstraction is -
Lets see an example-
The below Image shows a GUI of "Customer Details to be ADD-ed into a Database".
By looking at the Image we can say that we need a Customer Class.
Step - 1: What does my Customer Class needs?
i.e.
1 Function to Add the Customer Code and Customer Name into Database.
namespace CustomerContent { public class Customer { public string CustomerCode = ""; public string CustomerName = ""; public void ADD() { //my DB code will go here }
Now only ADD method wont work here alone.
Step -2: How will the validation work, ADD Function act?
We will need Database Connection code and Validation Code (Extra Methods).
public bool Validate()
{
//Granular Customer Code and Name
return true;
}
public bool CreateDBObject()
{
//DB Connection Code
return true;
}
class Program
{
static void main(String[] args)
{
CustomerComponent.Customer obj = new CustomerComponent.Customer;
obj.CustomerCode = "s001";
obj.CustomerName = "Mac";
obj.Validate();
obj.CreateDBObject();
obj.ADD();
}
}
Now there is no need of showing the Extra Methods(Validate(); CreateDBObject() [Complicated and Extra method] ) to the End User.End user only needs to see and know about Customer Code, Customer Name and ADD button which will ADD the record.. End User doesn't care about HOW it will ADD the Data to Database?.
Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction.
So making those Complicated and Extra method as Private instead Public(i.e Hiding those methods) and deleting the obj.Validate(); obj.CreateDBObject(); from main in class Program we achieve Encapsulation.
In other words Simplifying Interface to End User is Encapsulation.
So now the code looks like as below -
namespace CustomerContent
{
public class Customer
{
public string CustomerCode = "";
public string CustomerName = "";
public void ADD()
{
//my DB code will go here
}
private bool Validate()
{
//Granular Customer Code and Name
return true;
}
private bool CreateDBObject()
{
//DB Connection Code
return true;
}
class Program
{
static void main(String[] args)
{
CustomerComponent.Customer obj = new CustomerComponent.Customer;
obj.CustomerCode = "s001";
obj.CustomerName = "Mac";
obj.ADD();
}
}
Summary :
Step -1: What does my Customer Class needs? is Abstraction.
Step -3: Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction is Encapsulation.
P.S. - The code above is hard and fast.
The closest equivalent to Java's toString
is to implement __str__
for your class. Put this in your class definition:
def __str__(self):
return "foo"
You may also want to implement __repr__
to aid in debugging.
See here for more information:
after creating the view we have to add layout parameters .
change like this
TextView tv = new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
llview.addView(tv);
tv.setTextColor(Color.WHITE);
tv.setTextSize(2,25);
tv.setText(chat);
if (mine) {
leftMargin = 5;
tv.setBackgroundColor(0x7C5B77);
}
else {
leftMargin = 50;
tv.setBackgroundColor(0x778F6E);
}
final ViewGroup.MarginLayoutParams lpt =(MarginLayoutParams)tv.getLayoutParams();
lpt.setMargins(leftMargin,lpt.topMargin,lpt.rightMargin,lpt.bottomMargin);
I ran into a problem where the typical position: fixed
and bottom: 0
didn't work. Discovered a neat functionality with position: sticky
. Note it's "relatively" new so it won't with IE/Edge 15 and earlier.
Here's an example for w3schools.
<!DOCTYPE html>
<html>
<head>
<style>
div.sticky {
position: sticky;
bottom: 0;
background-color: yellow;
padding: 30px;
font-size: 20px;
}
</style>
</head>
<body>
<p>Lorem ipsum dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dlerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dlerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dlerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dlerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas </p>
<div class="sticky">I will stick to the screen when you reach my scroll position</div>
</body>
</html>
_x000D_
If you do not need to add a border on columns, you can also simply add a transparent border on them:
[class*="col-"] {
background-clip: padding-box;
border: 10px solid transparent;
}
StartDate = moment(StartDate).format('MM-YYYY');
...and MySQL date format:
StartDate = moment(StartDate).format('YYYY-MM-DD');
This is not subjective. Make sure your headers don't rely on being #include
d in specific order. You can be sure it doesn't matter what order you include STL or Boost headers.
Try this, your dot source was a little off. Edit, adding lastexitcode bits for OP.
$A = Start-Process -FilePath .\my-app\my-fle.bat -Wait -passthru;$a.ExitCode
add -WindowStyle Hidden
for invisible batch.
Using Array.prototype.map()
const zip = (a, b) => a.map((k, i) => [k, b[i]]);
console.log(zip([1,2,3], ["a","b","c"]));
// [[1, "a"], [2, "b"], [3, "c"]]
_x000D_
Using Array.from()
const zip = (a, b) => Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]]);
console.log( zip([1,2,3], ["a","b","c","d"]) );
// [[1, "a"], [2, "b"], [3, "c"], [undefined, "d"]]
_x000D_
Using Array.prototype.fill() and Array.prototype.map()
const zip = (a, b) => Array(Math.max(b.length, a.length)).fill().map((_,i) => [a[i], b[i]]);
console.log(zip([1,2,3], ["a","b","c","d"]));
// [[1, "a"], [2, "b"], [3, "c"], [undefined, 'd']]
_x000D_
If you are facing trouble while reverting back the migration, and somehow have messed it, you can perform fake
migrations.
./manage.py migrate <name> --ignore-ghost-migrations --merge --fake
For django version < 1.7 this will create entry in south_migrationhistory
table, you need to delete that entry.
Now you'll be able to revert back the migration easily.
PS: I was stuck for a lot of time and performing fake migration and then reverting back helped me out.
Following Pavel's advice to use a custom directive, here's a version that requires adding no payload to the routeConfig, is super declarative, and can be adapted to react to any level of the path, by simply changing which slice()
of it you're paying attention to.
app.directive('detectActiveTab', function ($location) {
return {
link: function postLink(scope, element, attrs) {
scope.$on("$routeChangeSuccess", function (event, current, previous) {
/*
Designed for full re-usability at any path, any level, by using
data from attrs. Declare like this:
<li class="nav_tab">
<a href="#/home" detect-active-tab="1">HOME</a>
</li>
*/
// This var grabs the tab-level off the attribute, or defaults to 1
var pathLevel = attrs.detectActiveTab || 1,
// This var finds what the path is at the level specified
pathToCheck = $location.path().split('/')[pathLevel] ||
"current $location.path doesn't reach this level",
// This var finds grabs the same level of the href attribute
tabLink = attrs.href.split('/')[pathLevel] ||
"href doesn't include this level";
// Above, we use the logical 'or' operator to provide a default value
// in cases where 'undefined' would otherwise be returned.
// This prevents cases where undefined===undefined,
// possibly causing multiple tabs to be 'active'.
// now compare the two:
if (pathToCheck === tabLink) {
element.addClass("active");
}
else {
element.removeClass("active");
}
});
}
};
});
We're accomplishing our goals by listening for the $routeChangeSuccess
event, rather than by placing a $watch
on the path. I labor under the belief that this means the logic should run less often, as I think watches fire on each $digest
cycle.
Invoke it by passing your path-level argument on the directive declaration. This specifies what chunk of the current $location.path() you want to match your href
attribute against.
<li class="nav_tab"><a href="#/home" detect-active-tab="1">HOME</a></li>
So, if your tabs should react to the base-level of the path, make the argument '1'. Thus, when location.path() is "/home", it will match against the "#/home" in the href
. If you have tabs that should react to the second level, or third, or 11th of the path, adjust accordingly. This slicing from 1 or greater will bypass the nefarious '#' in the href, which will live at index 0.
The only requirement is that you invoke on an <a>
, as the element is assuming the presence of an href
attribute, which it will compare to the current path. However, you could adapt fairly easily to read/write a parent or child element, if you preferred to invoke on the <li>
or something. I dig this because you can re-use it in many contexts by simply varying the pathLevel argument. If the depth to read from was assumed in the logic, you'd need multiple versions of the directive to use with multiple parts of the navigation.
EDIT 3/18/14: The solution was inadequately generalized, and would activate if you defined an arg for the value of 'activeTab' that returned undefined
against both $location.path()
, and the element's href
. Because: undefined === undefined
. Updated to fix that condition.
While working on that, I realized there should have been a version you can just declare on a parent element, with a template structure like this:
<nav id="header_tabs" find-active-tab="1">
<a href="#/home" class="nav_tab">HOME</a>
<a href="#/finance" class="nav_tab">Finance</a>
<a href="#/hr" class="nav_tab">Human Resources</a>
<a href="#/quarterly" class="nav_tab">Quarterly</a>
</nav>
Note that this version no longer remotely resembles Bootstrap-style HTML. But, it's more modern and uses fewer elements, so I'm partial to it. This version of the directive, plus the original, are now available on Github as a drop-in module you can just declare as a dependency. I'd be happy to Bower-ize them, if anybody actually uses them.
Also, if you want a bootstrap-compatible version that includes <li>
's, you can go with the angular-ui-bootstrap Tabs module, which I think came out after this original post, and which is perhaps even more declarative than this one. It's less concise for basic stuff, but provides you with some additional options, like disabled tabs and declarative events that fire on activate and deactivate.
Static member functions must refer to static variables of that class. So in your case,
static void CP_StringToPString( std::string& inString, unsigned char *outString);
Since your member function CP_StringToPstring
is static, the parameters in that function, inString
and outString
should be declared as static too.
The static member functions does not refer to the object that it is working on but the variables your declared refers to its current object so it return error.
You could either remove the static from the member function or add static while declaring the parameters you used for the member function as static too.
From - JQuery_Core_Style_Guidelines
Global Variables:
typeof variable === "undefined"
Local Variables:
variable === undefined
Properties:
object.prop === undefined
I had a similar requirement, and had to do it it basic CSS and JavaScript. No JQuery available.
This is what I got working.
<html>
<head>
<style>
img {
max-width: 95% !important;
max-height: 95% !important;
}
</style>
<script>
function FitImagesToScreen() {
var images = document.getElementsByTagName('img');
if(images.length > 0){
for(var i=0; i < images.length; i++){
if(images[i].width >= (window.innerWidth - 10)){
images[i].style.width = 'auto';
}
}
}
}
</script>
</head>
<body onload='FitImagesToScreen()'>
----
</body>
</html>
Note : I haven't used 100% for image width as there was always a bit of padding to be considered.
You could code an ES5.1 helper function:
function setAttributes(el, attrs) {
Object.keys(attrs).forEach(key => el.setAttribute(key, attrs[key]));
}
Call it like this:
setAttributes(elem, { src: 'http://example.com/something.jpeg', height: '100%' });
Create a new folder and run git init
in it.
Then try git remote add origin <your-repository-url>
.
Copy all the files in your project folder to the new folder, except the .git folder (it may be invisible).
Then you can push your code by doing:
git add --all
; or git add -A
;
git commit -m "YOUR MESSAGE"
;
git push -u origin master
.
I think it will work!
printf("\e[1;1H\e[2J");
This function will work on ANSI terminals, demands POSIX. I assume there is a version that might also work on window's console, since it also supports ANSI escape sequences.
#include <unistd.h>
void clearScreen()
{
const char *CLEAR_SCREEN_ANSI = "\e[1;1H\e[2J";
write(STDOUT_FILENO, CLEAR_SCREEN_ANSI, 12);
}
There are some other alternatives, some of which don't move the cursor to {1,1}.
For negative integer value, SIGNED
is used and for non-negative integer value, UNSIGNED
is used. It always suggested to use UNSIGNED
for id as a PRIMARY KEY.
You could try a subquery:
SELECT DISTINCT TEST.* FROM (
SELECT rsc.RadioServiceCodeId,
rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
FROM sbi_l_radioservicecodes rsc
INNER JOIN sbi_l_radioservicecodegroups rscg ON rsc.radioservicecodeid = rscg.radioservicecodeid
WHERE rscg.radioservicegroupid IN
(select val from dbo.fnParseArray(@RadioServiceGroup,','))
OR @RadioServiceGroup IS NULL
ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
) as TEST
$cfg['Servers'][$i]['host'] = '127.0.0.1:3307';
if u change port address
To make the child element positioned absolutely from its parent element you need to set relative position on the parent element AND absolute position on the child element.
Then on the child element 'top' is relative to the height of the parent. So you also need to 'translate' upward the child 50% of its own height.
.base{_x000D_
background-color: green;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
overflow: auto;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.vert-align {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
transform: translate(0, -50%);_x000D_
}
_x000D_
<div class="base">_x000D_
<div class="vert-align">_x000D_
Content Here_x000D_
</div>_x000D_
</div>
_x000D_
There is another a solution using flex box.
.base{_x000D_
background-color:green;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
overflow: auto;_x000D_
display: flex;_x000D_
align-items: center;_x000D_
}
_x000D_
<div class="base">_x000D_
<div class="vert-align">_x000D_
Content Here_x000D_
</div>_x000D_
</div>
_x000D_
You will find advantages/disavantages for both.
After some trial and tribulation, I was able to find all .msi files in a given directory and install them.
foreach($_msiFiles in
($_msiFiles = Get-ChildItem $_Source -Recurse | Where{$_.Extension -eq ".msi"} |
Where-Object {!($_.psiscontainter)} | Select-Object -ExpandProperty FullName))
{
msiexec /i $_msiFiles /passive
}
In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager
then find Xml Tools
plugin. Tick the box and click Install
Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now
).
Following dialog will open:
Click on ...
. Point to XSD file and I am pretty sure you'll be able to handle things from here.
Hope this saves you some time.
EDIT:
Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1
plugin manager is back under a different guise... Plugin Admin
so now you can simply update notepad++ and have it back.
$(document).ready(function() {_x000D_
_x000D_
$(window).scroll(function () {_x000D_
//if you hard code, then use console_x000D_
//.log to determine when you want the _x000D_
//nav bar to stick. _x000D_
console.log($(window).scrollTop())_x000D_
if ($(window).scrollTop() > 280) {_x000D_
$('#nav_bar').addClass('navbar-fixed');_x000D_
}_x000D_
if ($(window).scrollTop() < 281) {_x000D_
$('#nav_bar').removeClass('navbar-fixed');_x000D_
}_x000D_
});_x000D_
});
_x000D_
html, body {_x000D_
height: 4000px;_x000D_
}_x000D_
_x000D_
.navbar-fixed {_x000D_
top: 0;_x000D_
z-index: 100;_x000D_
position: fixed;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#body_div {_x000D_
top: 0;_x000D_
position: relative;_x000D_
height: 200px;_x000D_
background-color: green;_x000D_
}_x000D_
_x000D_
#banner {_x000D_
width: 100%;_x000D_
height: 273px;_x000D_
background-color: gray;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
#nav_bar {_x000D_
border: 0;_x000D_
background-color: #202020;_x000D_
border-radius: 0px;_x000D_
margin-bottom: 0;_x000D_
height: 30px;_x000D_
}_x000D_
_x000D_
.nav_links {_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.nav_links li {_x000D_
display: inline-block;_x000D_
margin-top: 4px;_x000D_
}_x000D_
.nav_links li a {_x000D_
padding: 0 15.5px;_x000D_
color: #3498db;_x000D_
text-decoration: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="banner">_x000D_
<h2>put what you want here</h2>_x000D_
<p>just adjust javascript size to match this window</p>_x000D_
</div>_x000D_
_x000D_
<nav id='nav_bar'>_x000D_
<ul class='nav_links'>_x000D_
<li><a href="url">Nav Bar</a></li>_x000D_
<li><a href="url">Sign In</a></li>_x000D_
<li><a href="url">Blog</a></li>_x000D_
<li><a href="url">About</a></li>_x000D_
</ul>_x000D_
</nav>_x000D_
<div id='body_div'>_x000D_
<p style='margin: 0; padding-top: 50px;'>and more stuff to continue scrolling here</p>_x000D_
</div>
_x000D_
All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.
If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED @ %s:%i\n", __FILE__, __LINE__);
) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.
It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)
exec does not execute a command in your shell
try
Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});
instead.
EDIT:: I don't have csh on my system so I used bash instead. The following worked for me
Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});
copy and paste this xml instead of your xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back1"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:background="@drawable/red">
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dropDownWidth="fill_parent"
android:background="@android:drawable/btn_dropdown"
/>
</LinearLayout>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignLeft="@+id/linearLayout1"
android:layout_alignRight="@+id/linearLayout1"
android:layout_below="@+id/linearLayout1"
android:layout_marginTop="25dp"
android:background="@drawable/red"
android:ems="10"
android:hint="enter card number" >
<requestFocus />
</EditText>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignLeft="@+id/editText1"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="33dp"
android:orientation="horizontal"
android:background="@drawable/red">
<Spinner
android:id="@+id/spinner3"
android:layout_width="72dp"
android:layout_height="wrap_content"
android:background="@android:drawable/btn_dropdown"
/>
<Spinner
android:id="@+id/spinner2"
android:layout_width="72dp"
android:layout_height="wrap_content"
android:background="@android:drawable/btn_dropdown"
/>
<EditText
android:id="@+id/editText2"
android:layout_width="22dp"
android:layout_height="match_parent"
android:layout_weight="0.18"
android:ems="10"
android:hint="enter cvv" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignRight="@+id/linearLayout2"
android:layout_below="@+id/linearLayout2"
android:layout_marginTop="26dp"
android:orientation="vertical"
android:background="@drawable/red" >
</LinearLayout>
<Spinner
android:id="@+id/spinner4"
android:layout_width="15dp"
android:layout_height="18dp"
android:layout_alignBottom="@+id/linearLayout3"
android:layout_alignLeft="@+id/linearLayout3"
android:layout_alignRight="@+id/linearLayout3"
android:layout_alignTop="@+id/linearLayout3"
android:background="@android:drawable/btn_dropdown"
/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/linearLayout3"
android:layout_marginTop="18dp"
android:text="Add Amount"
android:background="@drawable/buttonsty"/>
</RelativeLayout>
I just came across the same issue while trying to query a MySQL Database from Pentaho.
Error connecting to database [Local MySQL DB] : org.pentaho.di.core.exception.KettleDatabaseException: Error occured while trying to connect to the database
Exception while loading class org.gjt.mm.mysql.Driver
Expanding post by @user979331 the solution is:
copy the .jar file (mysql-connector-java-5.1.31-bin.jar) and paste it in your Lib folder:
PC: C:\Program Files\pentaho\design-tools\data-integration\lib
Mac: /Applications/data-integration/lib
Restart Pentaho (Data Integration) and re-test the MySQL Connection.
Additional interesting replies from others that could also help:
Laravel supports aliases on tables and columns with AS
. Try
$users = DB::table('really_long_table_name AS t')
->select('t.id AS uid')
->get();
Let's see it in action with an awesome tinker
tool
$ php artisan tinker [1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');}); // NULL [2] > DB::table('really_long_table_name')->insert(['id' => null]); // true [3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get(); // array( // 0 => object(stdClass)( // 'uid' => '1' // ) // )
It seems that you can't do all this in a trigger. According to the documentation:
Within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.
According to this answer, it seems that you should:
create a stored procedure, that inserts into/Updates the target table, then updates the other row(s), all in a transaction.
With a stored proc you'll manually commit the changes (insert and update). I haven't done this in MySQL, but this post looks like a good example.
Gitlab uses GitLab Flavored Markdown (GFM)
Here "all Markdown-rendered headers automatically get IDs"
One can use mouse to :
copy and save link using right mouse click
For example in README.md file I have header:
## series expansion formula of the Boettcher function
which gives a link :
Prefix can be removed so the link here is simply
file#header
which here means:
README.md#series-expansion-formula-of-the-boettcher-function
Now it can be used as :
[series expansion formula of the Boettcher function](README.md#series-expansion-formula-of-the-boettcher-function)
One can also do it manually: replace spaces with hyphen sign.
Live example is here
var str1 = 'abc';
var str2 = str1+' def'; // str2 is now 'abc def'
I use NUnit and in my project directory I have a copy of my App.Config that I change some configuration (example I redirect to a test database...). You need to have it in the same directory of the tested project and you will be fine.
Flexboxes can accomplish this by using align-items: flex-end;
with display: flex;
or display: inline-flex;
div#imageContainer {
height: 160px;
align-items: flex-end;
display: flex;
/* This is the default value, so you only need to explicitly set it if it's already being set to something else elsewhere. */
/*flex-direction: row;*/
}
I'm running under .NET 4.5.2, and I wasn't happy with any of these answers. As I'm talking to a system which supports TLS 1.2, and seeing as SSL3, TLS 1.0, and TLS 1.1 are all broken and unsafe for use, I don't want to enable these protocols. Under .NET 4.5.2, the SSL3 and TLS 1.0 protocols are both enabled by default, which I can see in code by inspecting ServicePointManager.SecurityProtocol
. Under .NET 4.7, there's the new SystemDefault
protocol mode which explicitly hands over selection of the protocol to the OS, where I believe relying on registry or other system configuration settings would be appropriate. That doesn't seem to be supported under .NET 4.5.2 however. In the interests of writing forwards-compatible code, that will keep making the right decisions even when TLS 1.2 is inevitably broken in the future, or when I upgrade to .NET 4.7+ and hand over more responsibility for selecting an appropriate protocol to the OS, I adopted the following code:
SecurityProtocolType securityProtocols = ServicePointManager.SecurityProtocol;
if (securityProtocols.HasFlag(SecurityProtocolType.Ssl3) || securityProtocols.HasFlag(SecurityProtocolType.Tls) || securityProtocols.HasFlag(SecurityProtocolType.Tls11))
{
securityProtocols &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11);
if (securityProtocols == 0)
{
securityProtocols |= SecurityProtocolType.Tls12;
}
ServicePointManager.SecurityProtocol = securityProtocols;
}
This code will detect when a known insecure protocol is enabled, and in this case, we'll remove these insecure protocols. If no other explicit protocols remain, we'll then force enable TLS 1.2, as the only known secure protocol supported by .NET at this point in time. This code is forwards compatible, as it will take into consideration new protocol types it doesn't know about being added in the future, and it will also play nice with the new SystemDefault
state in .NET 4.7, meaning I won't have to re-visit this code in the future. I'd strongly recommend adopting an approach like this, rather than hard-coding any particular security protocol states unconditionally, otherwise you'll have to recompile and replace your client with a new version in order to upgrade to a new security protocol when TLS 1.2 is inevitably broken, or more likely you'll have to leave the existing insecure protocols turned on for years on your server, making your organisation a target for attacks.
It doesn't seem to trigger DocumentCompleted/Navigated events for external Javascript or CSS files, but it will for iframes. As PK says, compare the WebBrowserDocumentCompletedEventArgs.Url property (I don't have the karma to make a comment yet).
If you control the type being used as dynamic, couldn't you return a tuple instead of a value for every property access? Something like...
public class DynamicValue<T>
{
internal DynamicValue(T value, bool exists)
{
Value = value;
Exists = exists;
}
T Value { get; private set; }
bool Exists { get; private set; }
}
Possibly a naive implementation, but if you construct one of these internally each time and return that instead of the actual value, you can check Exists
on every property access and then hit Value
if it does with value being default(T)
(and irrelevant) if it doesn't.
That said, I might be missing some knowledge on how dynamic works and this might not be a workable suggestion.
Checking for length is a good answer, but you could also account for an "empty" string that is also only whitespace. Not "technically" empty, but if you care to check:
package main
import (
"fmt"
"strings"
)
func main() {
stringOne := "merpflakes"
stringTwo := " "
stringThree := ""
if len(strings.TrimSpace(stringOne)) == 0 {
fmt.Println("String is empty!")
}
if len(strings.TrimSpace(stringTwo)) == 0 {
fmt.Println("String two is empty!")
}
if len(stringTwo) == 0 {
fmt.Println("String two is still empty!")
}
if len(strings.TrimSpace(stringThree)) == 0 {
fmt.Println("String three is empty!")
}
}
For me the solution was to add the registry to here:
/etc/sysconfig/docker-registries
DOCKER_REGISTRIES=''
DOCKER_EXTRA_REGISTRIES='--insecure-registry b.example.com'
in Eclipse 4.4.1
com.soft4soft.resort.jdt,2.4.4,file:plugins\com.soft4soft.resort.jdt_2.4.4.jar,4,false
This is in deed due to characters messing around with the data. Using htmlentities($yourText)
worked for me (I had html code inside the xml document). See http://uk3.php.net/htmlentities.
Yet another catch I ran into: ensure your Installer derived class (typically ProjectInstaller
) is at the top of the namespace hierarchy, I tried to use a public class within another public class, but this results in the same old error:
No public installers with the RunInstallerAttribute.Yes attribute could be found
Install using pip install pycompyle6
pycompyle6 filename.pyc
Let v be the starting vertex
Let G be the graph in question
The following is the pseudo code without using queue
Initially label v as visited as you start from v
BFS(G,v)
for all adjacent vertices w of v in G:
if vertex w is not visited:
label w as visited
for all adjacent vertices w of v in G:
recursively call BFS(G,w)
Inputs -
tableView.beginUpdates() tableView.endUpdates() these functions will not call
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {}
But, if you do, tableView.reloadRows(at: [selectedIndexPath! as IndexPath], with: .none)
It will call the func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {} this function.
I've created a library that uses multipart uploads in the background to avoid buffering everything in memory and also doesn't write to disk: https://github.com/alexmojaki/s3-stream-upload
As of today, there is an official Android-hosted copy of Volley available on JCenter:
compile 'com.android.volley:volley:1.0.0'
This was compiled from the AOSP volley source code.
Here is part of a line in my code that brought the warning up in NetBeans:
$page = (!empty($_GET['p']))
After much research and seeing how there are about a bazillion ways to filter this array, I found one that was simple. And my code works and NetBeans is happy:
$p = filter_input(INPUT_GET, 'p');
$page = (!empty($p))
Try this, but i don't sure that will work every where :)
public enum MyEnum {
A("Start There"),
B("Start Here");
MyEnum(String name) {
try {
Field fieldName = getClass().getSuperclass().getDeclaredField("name");
fieldName.setAccessible(true);
fieldName.set(this, name);
fieldName.setAccessible(false);
} catch (Exception e) {}
}
}
TreeMap
is your best bet for these kind of sorting (Natural). TreeMap
naturally sorts according to the keys.
HashMap
does not preserve insertion order nor does it sort the map. LinkedHashMap
keeps the insertion order but doesn't sort the map automatically. Only TreeMap
in the Map
interface sorts the map according to natural order (Numerals first, upper-case alphabet second, lower-case alphabet last).
I recently put all my source on a windows 8 32 box. Had the issues loading mscomctl.ocx
with existing projects.
I created a new project and add the common control (all). save the project and reloaded it no problem.
when you compare the project headers new vs old the old one uses reference=*\blah blah. I found removing this a replacing it with the Object={blah} sorted out the problem.
Yes. Please see the man page of bash ( the first thing you go to ) under Special Parameters
Special Parameters
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.
*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is,"$*"
is equivalent to"$1c$2c..."
, wherec
is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is,"$@"
is equivalent to"$1"
"$2"
... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters,"$@"
and$@
expand to nothing (i.e., they are removed).
In my situation, in order to include color.sh
from the same directory in init.sh
, I had to do something as follows.
. ./color.sh
Not sure why the ./
and not color.sh
directly. The content of color.sh
is as follows.
RED=`tput setaf 1`
GREEN=`tput setaf 2`
BLUE=`tput setaf 4`
BOLD=`tput bold`
RESET=`tput sgr0`
Making use of File color.sh
does not error but, the color do not display. I have tested this in Ubuntu 18.04
and the Bash
version is:
GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)
When you do
$array_x = $array_y;
PHP copies the array, so I'm not sure how you would have gotten burned. For your case,
global $foo;
$foo = $obj->bar;
should work fine.
In order to get burned, I would think you'd either have to have been using references or expecting objects inside the arrays to be cloned.
A pixel is the smallest unit value to render something with, but you can trick thickness with optical illusions by modifying colors (the eye can only see up to a certain resolution too).
Here is a test to prove this point:
div { border-color: blue; border-style: solid; margin: 2px; }
div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: rgb(160,160,255); }
_x000D_
<div class="b1">Some text</div>
<div class="b2">Some text</div>
<div class="b3">Some text</div>
<div class="b4">Some text</div>
_x000D_
Which gives the illusion that the last DIV
has a smaller border width, because the blue border blends more with the white background.
Alpha values may also be used to simulate the same effect, without the need to calculate and manipulate RGB values.
.container {
border-style: solid;
border-width: 1px;
margin-bottom: 10px;
}
.border-100 { border-color: rgba(0,0,255,1); }
.border-75 { border-color: rgba(0,0,255,0.75); }
.border-50 { border-color: rgba(0,0,255,0.5); }
.border-25 { border-color: rgba(0,0,255,0.25); }
_x000D_
<div class="container border-100">Container 1 (alpha = 1)</div>
<div class="container border-75">Container 2 (alpha = 0.75)</div>
<div class="container border-50">Container 3 (alpha = 0.5)</div>
<div class="container border-25">Container 4 (alpha = 0.25)</div>
_x000D_
I'm pretty certain it is because the DbContext is not at all thread safe. So sharing the thing is never a good idea.