x86 refers to the Intel processor architecture that was used in PCs. Model numbers were 8088 (8 bit bus version of 8086 and used in the first IBM PC), 8086, 286, 386, 486. After which they switched to names instead of numbers to stop AMD from copying the processor names. Pentium etc, never a Hexium :).
x64 is the architecture name for the extensions to the x86 instruction set that enable 64-bit code. Invented by AMD and later copied by Intel when they couldn't get their own 64-bit arch to be competitive, Itanium didn't fare well. Other names for it are x86_64, AMD's original name and commonly used in open source tools. And amd64, AMD's next name and commonly used in Microsoft tools. Intel's own names for it (EM64T and "Intel 64") never caught on.
x32 is a fuzzy term that's not associated with hardware. It tends to be used to mean "32-bit" or "32-bit pointer architecture", Linux has an ABI by that name.
ABI
- Application Binary Interface
is about a machine code communication in runtime between two binary parts like - application, library, OS... ABI
describes how objects are saved in memory, how functions are called(calling convention
), mangling...
A good example of API and ABI is iOS ecosystem with Swift language.
Application layer
- When you create an application using different languages. For example you can create application using Swift
and Objective-C
[Mixing Swift and Objective-C]
Application - OS layer
- runtime - Swift runtime
and standard libraries
are parts of OS and they should not be included into each bundle(e.g. app, framework). It is the same as like Objective-C uses
Library layer
- Module Stability
case - compile time - you will be able to import a framework which was built with another version of Swift's compiler. It means that it is safety to create a closed-source(pre-build) binary which will be consumed by a different version of compiler( .swiftinterface
is used with .swiftmodule
) and you will not get
Module compiled with _ cannot be imported by the _ compiler
Library layer
- Library Evolution
case
Calling conventions defines how parameters are passed in the registers when calling or being called by other program. And the best source of these convention is in the form of ABI standards defined for each these hardware. For ease of compilation, the same ABI is also used by userspace and kernel program. Linux/Freebsd follow the same ABI for x86-64 and another set for 32-bit. But x86-64 ABI for Windows is different from Linux/FreeBSD. And generally ABI does not differentiate system call vs normal "functions calls". Ie, here is a particular example of x86_64 calling conventions and it is the same for both Linux userspace and kernel: http://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64/ (note the sequence a,b,c,d,e,f of parameters):
Performance is one of the reasons for these ABI (eg, passing parameters via registers instead of saving into memory stacks)
For ARM there is various ABI:
http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.subset.swdev.abi/index.html
ARM64 convention:
http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
For Linux on PowerPC:
http://refspecs.freestandards.org/elf/elfspec_ppc.pdf
http://www.0x04.net/doc/elf/psABI-ppc64.pdf
And for embedded there is the PPC EABI:
http://www.freescale.com/files/32bit/doc/app_note/PPCEABI.pdf
This document is good overview of all the different conventions:
Caller-Saved (AKA volatile or call-clobbered) Registers
Callee-Saved (AKA non-volatile or call-preserved) Registers
boost 1.46.0 and up includes the Chrono library:
thread_clock class provides access to the real thread wall-clock, i.e. the real CPU-time clock of the calling thread. The thread relative current time can be obtained by calling thread_clock::now()
#include <boost/chrono/thread_clock.hpp>
{
...
using namespace boost::chrono;
thread_clock::time_point start = thread_clock::now();
...
thread_clock::time_point stop = thread_clock::now();
std::cout << "duration: " << duration_cast<milliseconds>(stop - start).count() << " ms\n";
You can also use inspect.getdoc
. It cleans up the __doc__
by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.
In SQL Server Management Studio 2016, perform the following:
Right click on database
Click delete
Check close existing connections
Perform delete operation
You could use the ternary operator:
return string.IsNullOrEmpty(strTestString) ? "0" : strTestString
FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;
In Kotlin you can do as
val videoView = findViewById<VideoView>(R.id.videoView)
// If url is from raw
/* val url = "android.resource://" + packageName
.toString() + "/" + R.raw.video*/
// If url is from network
val url = "http://www.servername.com/projects/projectname/videos/1361439400.mp4"
val video =
Uri.parse(url)
videoView.setVideoURI(video)
videoView.setOnPreparedListener{
videoView.start()
}
The easiest way is to use Math library.
Use Math.pow(a, b)
and the result will be a^b
If you want to do it yourself, you have to use for-loop
// Works only for b >= 1
public static double myPow(double a, int b){
double res =1;
for (int i = 0; i < b; i++) {
res *= a;
}
return res;
}
Using:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
Here is an extension function to do the split with a string separator:
public static string[] Split(this string value, string seperator)
{
return value.Split(new string[] { seperator }, StringSplitOptions.None);
}
Example of usage:
string mystring = "one[split on me]two[split on me]three[split on me]four";
var splitStrings = mystring.Split("[split on me]");
You can use read-tree
to read or merge a given remote tree into the current index, for example:
git remote add foo [email protected]/foo.git
git fetch foo
git read-tree --prefix=my-folder/ -u foo/master:trunk/their-folder
To perform the merge, use -m
instead.
See also: How do I merge a sub directory in Git?
This worked for me, use the VM args in NetBeans:
@Value("${a.b.c:#{abc}}"
...
@Value("${e.f.g:#{efg}}"
...
Netbeans:
-Da.b.c="..." -De.f.g="..."
Properties -> Run -> VM Options -> -De.f.g=efg -Da.b.c=abc
From the commandline
java -jar <yourjar> --Da.b.c="abc"
I am working in Windows 7 with Python IDLE. I have two programs,
# progA
while True:
m = input('progA is running ')
print (m)
and
# progB
while True:
m = input('progB is running ')
print (m)
I open up IDLE and then open file progA.py. I run the program, and when prompted for input I enter "b" + <Enter>
and then "c" + <Enter>
I am looking at this window:
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progA.py =
progA is running b
b
progA is running c
c
progA is running
Next, I go back to Windows Start and open up IDLE again, this time opening file progB.py. I run the program, and when prompted for input I enter "x" + <Enter>
and then "y" + <Enter>
I am looking at this window:
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progB.py =
progB is running x
x
progB is running y
y
progB is running
Now two IDLE Python 3.6.3 Shell programs are running at the same time, one shell running progA while the other one is running progB.
If you are using Ubuntu 14.04 ffmpeg
is not available. You can install it by using the instructions directly from https://www.ffmpeg.org/download.html.
In short you will have to:
sudo add-apt-repository ppa:mc3man/trusty-media
sudo apt-get update
sudo apt-get install ffmpeg gstreamer0.10-ffmpeg
If this does not work maybe try using sudo apt-get dist-upgrade
but this may broke things in your system.
Right click on the spring boot project -> debug as -> spring boot App
. Put a debugger point and invoke the app from a client like postman
Try to use minus sign for count from backside
<script>
$(document).ready(function () {
$('#example-2').DataTable({
'order':[],
'columnDefs': [{
"targets": [-1],
"orderable": false
}]
});
});
</script>
You can realize this layout using CSS table-cells.
Modify your HTML slightly as follows:
<div id="header">
<div class="container">
<div class="logoBar">
<img src="http://placehold.it/50x40" />
</div>
<div id="searchBar">
<input type="text" />
</div>
<div class="button orange" id="myAccount">My Account</div>
<div class="button red" id="basket">Basket (2)</div>
</div>
</div>
Just remove the wrapper element around the two .button
elements.
Apply the following CSS:
#header {
background-color: #323C3E;
width:100%;
}
.container {
display: table;
width: 100%;
}
.logoBar, #searchBar, .button {
display: table-cell;
vertical-align: middle;
width: auto;
}
.logoBar img {
display: block;
}
#searchBar {
background-color: #FFF2BC;
width: 90%;
padding: 0 50px 0 10px;
}
#searchBar input {
width: 100%;
}
.button {
white-space: nowrap;
padding:22px;
}
Apply display: table
to .container
and give it 100% width.
For .logoBar
, #searchBar
, .button
, apply display: table-cell
.
For the #searchBar
, set the width to 90%, which force all the other elements to compute a shrink-to-fit width and the search bar will expand to fill in the rest of the space.
Use text-align and vertical-align in the table cells as needed.
See demo at: http://jsfiddle.net/audetwebdesign/zWXQt/
I tried to work out your question with a switch statement but I still required a for loop to parse the string . feel free to comment if I can improve the code
public class CharacterCount {
public static void main(String args[])
{
String message="hello how are you";
char[] array=message.toCharArray();
int a=0;
int b=0;
int c=0;
int d=0;
int e=0;
int f=0;
int g=0;
int h=0;
int i=0;
int space=0;
int j=0;
int k=0;
int l=0;
int m=0;
int n=0;
int o=0;
int p=0;
int q=0;
int r=0;
int s=0;
int t=0;
int u=0;
int v=0;
int w=0;
int x=0;
int y=0;
int z=0;
for(char element:array)
{
switch(element)
{
case 'a':
a++;
break;
case 'b':
b++;
break;
case 'c':c++;
break;
case 'd':d++;
break;
case 'e':e++;
break;
case 'f':f++;
break;
case 'g':g++;
break;
case 'h':
h++;
break;
case 'i':i++;
break;
case 'j':j++;
break;
case 'k':k++;
break;
case 'l':l++;
break;
case 'm':m++;
break;
case 'n':m++;
break;
case 'o':o++;
break;
case 'p':p++;
break;
case 'q':q++;
break;
case 'r':r++;
break;
case 's':s++;
break;
case 't':t++;
break;
case 'u':u++;
break;
case 'v':v++;
break;
case 'w':w++;
break;
case 'x':x++;
break;
case 'y':y++;
break;
case 'z':z++;
break;
case ' ':space++;
break;
default :break;
}
}
System.out.println("A "+a+" B "+ b +" C "+c+" D "+d+" E "+e+" F "+f+" G "+g+" H "+h);
System.out.println("I "+i+" J "+j+" K "+k+" L "+l+" M "+m+" N "+n+" O "+o+" P "+p);
System.out.println("Q "+q+" R "+r+" S "+s+" T "+t+" U "+u+" V "+v+" W "+w+" X "+x+" Y "+y+" Z "+z);
System.out.println("SPACE "+space);
}
}
TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.
If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.
As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT
header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/chainedcert.pem; # server certificate
ssl_certificate_key /path/to/key; # server key
ssl_client_certificate /path/to/ca.pem; # client CA
ssl_verify_client on;
proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;
location / {
proxy_pass http://localhost:3000;
}
}
In Versions under Mac OS: Action -> Cleanup working copy locks at...
If you are using Sublime Text 3, using a build system to open the file opens the most current version and provides a convenient way to load it via [CTRL + B] To set up a build system that opens the file in chrome:
Go to 'Tools'
Hover your mouse over 'build system'. At the bottom of the list brought up, click 'New Build System...'
In the new build system file type this:
{"cmd": [ "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "$file"]}
**provided the path stated above in the first set of quotes is the path to where chrome is located on your computer, if it isn't simply find the location of chrome and replace the path in the first set of quotes with the path to chrome on your computer.
You must first validate if the input is actually an integer. You can do it with Integer.TryParse
:
Dim intValue As Integer
If Integer.TryParse(TxtBox.Text, intValue) AndAlso intValue > 0 AndAlso intValue < 11 Then
MessageBox.Show("Thank You, your rating was " & TxtBox.Text)
Else
MessageBox.Show("Please Enter a Number from 1 to 10")
End If
I'm guessing that you meant to do this:
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
# To concatenate strings in python, use ^
Another thing that can cause this error is creating a model with the centering/scaling standardize function from the arm package -- m <- standardize(lm(y ~ x, data = train))
If you then try predict(m)
, you get the same error as in this question.
No need for external plugins. In the Export JAR dialog, make sure you select all the necessary resources you want to export. By default, there should be no problem exporting other resource files as well (pictures, configuration files, etc...), see screenshot below.
If you want to rotate a vector you should construct what is known as a rotation matrix.
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
Likewise, I saw this error as a result of too little RAM. I cranked up the RAM on the VM and the error disappeared.
The statement def foo(client_id: str) -> list or bool:
when evaluated is equivalent to
def foo(client_id: str) -> list:
and will therefore not do what you want.
The native way to describe a "either A or B" type hint is Union (thanks to Bhargav Rao):
def foo(client_id: str) -> Union[list, bool]:
I do not want to be the "Why do you want to do this anyway" guy, but maybe having 2 return types isn't what you want:
If you want to return a bool to indicate some type of special error-case, consider using Exceptions instead. If you want to return a bool as some special value, maybe an empty list would be a good representation.
You can also indicate that None
could be returned with Optional[list]
There are two ways possible to this that I know:
Get the Processor id of the system:
public string getCPUId()
{
string cpuInfo = string.Empty;
ManagementClass mc = new ManagementClass("win32_processor");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (cpuInfo == "")
{
//Get only the first CPU's ID
cpuInfo = mo.Properties["processorID"].Value.ToString();
break;
}
}
return cpuInfo;
}
Get UUID of the system:
public string getUUID()
{
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "CMD.exe";
startInfo.Arguments = "/C wmic csproduct get UUID";
process.StartInfo = startInfo;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.WaitForExit();
string output = process.StandardOutput.ReadToEnd();
return output;
}
I tend to use the Information_Schema:
IF EXISTS ( SELECT 1
FROM Information_schema.Routines
WHERE Specific_schema = 'dbo'
AND specific_name = 'Foo'
AND Routine_Type = 'FUNCTION' )
for functions, and change Routine_Type
for stored procedures
IF EXISTS ( SELECT 1
FROM Information_schema.Routines
WHERE Specific_schema = 'dbo'
AND specific_name = 'Foo'
AND Routine_Type = 'PROCEDURE' )
The typical way to check for existence in many STL containers such as std::map
, std::set
, ... is:
const bool is_in = container.find(element) != container.end();
The question is: how to select the last column of a dataframe ? Appart @piRSquared, none answer the question.
the simplest way to get a dataframe with the last column is:
df.iloc[ :, -1:]
LocalDate ld ....;
LocalDateTime ldtime ...;
ld.isEqual(LocalDate.from(ldtime));
I know it's already an old question, but i had the same error today. For me setting the connection variable on model did the work.
/**
* Table properties
*/
protected $connection = 'mysql-utf8';
protected $table = 'notification';
protected $primaryKey = 'id';
I don't know if the issue was with the database (probably), but the texts fields with special chars (like ~, ´ e etc) were all messed up.
---- Editing
That $connection var is used to select wich db connection your model will use. Sometimes it happens that in database.php (under /config folder) you have multiples connections and the default one is not using UTF-8 charset.
In any case, be sure to properly use charset and collation into your connection.
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'your_database'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'database_password'),
'unix_socket' => env('DB_SOCKET', ''),
'prefix' => '',
'strict' => false,
'engine' => null
],
'mysql-utf8' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'your_database'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'database_password'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null
],
Yes, you can log queries to a special phpMyAdmin DB table.
See SQL_history.
I've found that the solution the works best for me is to just perform the merge and abort it if there are conflicts. This particular syntax feels clean and simple to me. This is Strategy 2 below.
However, if you want to ensure you don't mess up your current branch, or you're just not ready to merge regardless of the existence of conflicts, simply create a new sub-branch off of it and merge that:
git checkout mybranch
git checkout -b mynew-temporary-branch
git merge some-other-branch
That way you can simply throw away the temporary branch if you just want to see what the conflicts are. You don't need to bother "aborting" the merge, and you can go back to your work -- simply checkout 'mybranch' again and you won't have any merged code or merge conflicts in your branch.
This is basically a dry-run.
git checkout mybranch
git merge some-other-branch
If git reports conflicts (and ONLY IF THERE ARE conflicts) you can then do:
git merge --abort
If the merge is successful, you cannot abort it (only reset).
If you're not ready to merge, use the safer way above.
[EDIT: 2016-Nov - I swapped strategy 1 for 2, because it seems to be that most people are looking for "the safe way". Strategy 2 is now more of a note that you can simply abort the merge if the merge has conflicts that you're not ready to deal with. Keep in mind if reading comments!]
If you are using a String
build config field in your project, this might be the case:
buildConfigField "String", "source", "play"
If you declare your String like above it will cause the error to happen. The fix is to change it to:
buildConfigField "String", "source", "\"play\""
If I understand the question correctly, you want the equivalent of decode but in T-SQL
Select YourFieldAliasName =
CASE PC_SL_LDGR_CODE
WHEN '02' THEN 'DR'
ELSE 'CR'
END
You can use your selector with :not
like bellow you can use any selector inside the :not()
any_CSS_selector:not(any_other_CSS_selector){
/*YOUR STYLE*/
}
you can use
:not
without parent selector as well.
:not(:nth-child(2)){
/*YOUR STYLE*/
}
More examples
any_CSS_selector:not(:first-child){
/*YOUR STYLE*/
}
any_CSS_selector:not(:first-of-type){
/*YOUR STYLE*/
}
any_CSS_selector:not(:checked){
/*YOUR STYLE*/
}
any_CSS_selector:not(:last-child){
/*YOUR STYLE*/
}
any_CSS_selector:not(:last-of-type){
/*YOUR STYLE*/
}
any_CSS_selector:not(:first-of-type){
/*YOUR STYLE*/
}
any_CSS_selector:not(:nth-last-of-type(2)){
/*YOUR STYLE*/
}
any_CSS_selector:not(:nth-last-child(2)){
/*YOUR STYLE*/
}
any_CSS_selector:not(:nth-child(2)){
/*YOUR STYLE*/
}
Most of the methods works, but the excel process always stay until close the appliation.
When kill excel process once it can't be executed once again in the same thread - don't know why.
You can view these with Process Explorer from sysinternals. Use the "Find -> Find Handle or DLL..." option and enter the pattern "\Device\NamedPipe\". It will show you which processes have which pipes open.
You could use RichardSzalay MockHttp library which mocks the HttpMessageHandler and can return an HttpClient object to be used during tests.
PM> Install-Package RichardSzalay.MockHttp
MockHttp defines a replacement HttpMessageHandler, the engine that drives HttpClient, that provides a fluent configuration API and provides a canned response. The caller (eg. your application's service layer) remains unaware of its presence.
var mockHttp = new MockHttpMessageHandler();
// Setup a respond for the user api (including a wildcard in the URL)
mockHttp.When("http://localhost/api/user/*")
.Respond("application/json", "{'name' : 'Test McGee'}"); // Respond with JSON
// Inject the handler or client into your application code
var client = mockHttp.ToHttpClient();
var response = await client.GetAsync("http://localhost/api/user/1234");
// or without async: var response = client.GetAsync("http://localhost/api/user/1234").Result;
var json = await response.Content.ReadAsStringAsync();
// No network connection required
Console.Write(json); // {'name' : 'Test McGee'}
2-D Array Dynamic Memory Allocation
int **a,i;
// for any number of rows & columns this will work
a = (int **)malloc(rows*sizeof(int *));
for(i=0;i<rows;i++)
*(a+i) = (int *)malloc(cols*sizeof(int));
Check out this MD5 implementation for JavaScript. Its BSD Licensed and really easy to use. Example:
md5 = hex_md5("message to digest")
Use random.choice()
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
For cryptographically secure random choices (e.g. for generating a passphrase from a wordlist) use secrets.choice()
import secrets
foo = ['battery', 'correct', 'horse', 'staple']
print(secrets.choice(foo))
secrets
is new in Python 3.6, on older versions of Python you can use the random.SystemRandom
class:
import random
secure_random = random.SystemRandom()
print(secure_random.choice(foo))
You are using setTimeout
wrong way. The (one of) function signature is setTimeout(callback, delay)
. So you can easily specify what code should be run after what delay.
var codeAddress = (function() {
var index = 0;
var delay = 100;
function GeocodeCallback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
new google.maps.Marker({ map: map, position: results[0].geometry.location, animation: google.maps.Animation.DROP });
console.log(results);
}
else alert("Geocode was not successful for the following reason: " + status);
};
return function(vPostCode) {
if (geocoder) setTimeout(geocoder.geocode.bind(geocoder, { 'address': "'" + vPostCode + "'"}, GeocodeCallback), index*delay);
index++;
};
})();
This way, every codeAddress()
call will result in geocoder.geocode()
being called 100ms later after previous call.
I also added animation to marker so you will have a nice animation effect with markers being added to map one after another. I'm not sure what is the current google limit, so you may need to increase the value of delay
variable.
Also, if you are each time geocoding the same addresses, you should instead save the results of geocode to your db and next time just use those (so you will save some traffic and your application will be a little bit quicker)
400 Bad request Error will be thrown due to incorrect authentication entries.
Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.
Try with:
$row = mysqli_fetch_assoc($result);
echo "my result <a href='data/" . htmlentities($row['classtype'], ENT_QUOTES, 'UTF-8') . ".php'>My account</a>";
UseEnvironment.NewLine
instead of vbcrlf
In Python one would usually use lists for this purpose. Lists can be nested arbitrarily, thus allowing the creation of a 2D array. Not every sublist needs to be the same size, so that solves your other problem. Have a look at the examples I linked to.
The $(document).ready()
is a jQuery event which occurs when the HTML document has been fully loaded, while the window.onload
event occurs later, when everything including images on the page loaded.
Also window.onload is a pure javascript event in the DOM, while the $(document).ready()
event is a method in jQuery.
$(document).ready()
is usually the wrapper for jQuery to make sure the elements all loaded in to be used in jQuery...
Look at to jQuery source code to understand how it's working:
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
Also I have created the image below as a quick references for both:
Try this to read a file:
BufferedReader reader = null;
try {
File file = new File("sample-file.dat");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Just for completeness. There is another situation causing this error:
missing META-INF/services/javax.persistence.spi.PersistenceProvider file.
For Hibernate, it's located in hibernate-entitymanager-XXX.jar
, so, if hibernate-entitymanager-XXX.jar
is not in your classpath, you will got this error too.
This error message is so misleading, and it costs me hours to get it correct.
See JPA 2.0 using Hibernate as provider - Exception: No Persistence provider for EntityManager.
document.addEventListener('touchstart', function(e) {e.preventDefault()}, false);
document.addEventListener('touchmove', function(e) {e.preventDefault()}, false);
This should prevent scrolling, but it will also break other touch events unless you define a custom way to handle them.
i had a similar issue using enum with switch cases later i resolved it on my own....below is the corrected code, perhaps this might help.
//Menu Chooser Programe using enum
#include<iostream>
using namespace std;
int main()
{
enum level{Novice=1, Easy, Medium, Hard};
level diffLevel=Novice;
int i;
cout<<"\nenter a level: ";
cin>>i;
switch(i)
{
case Novice: cout<<"\nyou picked Novice\n"; break;
case Easy: cout<<"\nyou picked Easy\n"; break;
case Medium: cout<<"\nyou picked Medium\n"; break;
case Hard: cout<<"\nyou picked Hard\n"; break;
default: cout<<"\nwrong input!!!\n"; break;
}
return 0;
}
Try instead of db.parse(xml)
:
Document doc = db.parse(new InputSource(new StringReader(**xml**)));
System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream);
reader.BaseStream.Position = 0;
string requestFromPost = reader.ReadToEnd();
As i've mentioned in other, similar questions, you may want to consider compressing the data as the default java serialization is a bit verbose. you do this by putting a GZIPInput/OutputStream between the Object streams and the Byte streams.
int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");
Simply create an instance of Class2
and call the desired method.
Suggested reading: http://docs.oracle.com/javase/tutorial/java/javaOO/
You can use this method:
For the links if you use linkText();
it is more effective than the any other locator.
driver.findElement(By.linkText("App Configuration")).click();
There certainly is nothing in the language that enforces it in any way. I tend to group things by visibility (public, then protected, then private) and use #regions to group related things functionally, regardless of whether it is a property, method, or whatever. Construction methods (whether actual ctors or static factory functions) are usually right at the top since they are the first thing clients need to know about.
Normally speaking you'd use a DB manager application like pgAdmin, browse to the object you're interested in, and right click your way to "script as create" or similar.
Are you trying to do this... without a management app?
For doing "normal" hash table lookups on basically any kind of data - this one by Paul Hsieh is the best I've ever used.
http://www.azillionmonkeys.com/qed/hash.html
If you care about cryptographically secure or anything else more advanced, then YMMV. If you just want a kick ass general purpose hash function for a hash table lookup, then this is what you're looking for.
I have resolve the problem as below 1. Get the tag from your branch 2. Write below command
Example: git branch <Hotfix branch> <TAG>
git branch hotfix_4.4.3 v4.4.3
git checkout hotfix_4.4.3
or you can do with other command
git checkout -b <Hotfix branch> <TAG>
-b stands for creating new branch to local
once you ready with your hotfix branch, It's time to move that branch to github, you can do so by writing below command
git push --set-upstream origin hotfix_4.4.3
btnSubmit_Click(btnSubmit,EventArgs.Empty);
Perhaps this example could explain.
CREATE TABLE `test`(`fla` FLOAT,`flb` FLOAT,`dba` DOUBLE(10,2),`dbb` DOUBLE(10,2));
We have a table like this:
+-------+-------------+
| Field | Type |
+-------+-------------+
| fla | float |
| flb | float |
| dba | double(10,2)|
| dbb | double(10,2)|
+-------+-------------+
For first difference, we try to insert a record with '1.2' to each field:
INSERT INTO `test` values (1.2,1.2,1.2,1.2);
The table showing like this:
SELECT * FROM `test`;
+------+------+------+------+
| fla | flb | dba | dbb |
+------+------+------+------+
| 1.2 | 1.2 | 1.20 | 1.20 |
+------+------+------+------+
See the difference?
We try to next example:
SELECT fla+flb, dba+dbb FROM `test`;
Hola! We can find the difference like this:
+--------------------+---------+
| fla+flb | dba+dbb |
+--------------------+---------+
| 2.4000000953674316 | 2.40 |
+--------------------+---------+
// Sort Array of Objects
// Data
var booksArray = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
// Property to Sort By
var args = "last_nom";
// Function to Sort the Data by given Property
function sortByProperty(property) {
return function (a, b) {
var sortStatus = 0,
aProp = a[property].toLowerCase(),
bProp = b[property].toLowerCase();
if (aProp < bProp) {
sortStatus = -1;
} else if (aProp > bProp) {
sortStatus = 1;
}
return sortStatus;
};
}
// Implementation
var sortedArray = booksArray.sort(sortByProperty(args));
console.log("sortedArray: " + JSON.stringify(sortedArray) );
Console log output:
"sortedArray:
[{"first_nom":"Pig","last_nom":"Bodine"},
{"first_nom":"Lazslo","last_nom":"Jamf"},
{"first_nom":"Pirate","last_nom":"Prentice"}]"
Adapted based on this source: http://www.levihackwith.com/code-snippet-how-to-sort-an-array-of-json-objects-by-property/
The following works for me, after much trial
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<id>xjc1</id>
<goals>
<goal>xjc</goal>
</goals>
<configuration>
<packageName>com.mycompany.clientSummary</packageName>
<sourceType>wsdl</sourceType>
<sources>
<source>src/main/resources/wsdl/GetClientSummary.wsdl</source>
</sources>
<outputDirectory>target/generated-sources/xjb</outputDirectory>
<clearOutputDir>false</clearOutputDir>
</configuration>
</execution>
<execution>
<id>xjc2</id>
<goals>
<goal>xjc</goal>
</goals>
<configuration>
<packageName>com.mycompany.wsclient.employerProfile</packageName>
<sourceType>wsdl</sourceType>
<sources>
<source>src/main/resources/wsdl/GetEmployerProfile.wsdl</source>
</sources>
<outputDirectory>target/generated-sources/xjb</outputDirectory>
<clearOutputDir>false</clearOutputDir>
</configuration>
</execution>
<execution>
<id>xjc3</id>
<goals>
<goal>xjc</goal>
</goals>
<configuration>
<packageName>com.mycompany.wsclient.producersLicenseData</packageName>
<sourceType>wsdl</sourceType>
<sources>
<source>src/main/resources/wsdl/GetProducersLicenseData.wsdl</source>
</sources>
<outputDirectory>target/generated-sources/xjb</outputDirectory>
<clearOutputDir>false</clearOutputDir>
</configuration>
</execution>
</executions>
</plugin>
It would be fairly easy to force the web browser to display the page with the same pixel dimensions as A4. However, there may be a few quirks when things are rendered.
Assuming your monitors display 72 dpi, you could add something like this:
<!DOCTYPE html>
<html>
<head>
<style>
body {
height: 842px;
width: 595px;
/* to centre page on screen*/
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
</body>
</html>
_msize(array)
in Windows or malloc_usable_size(array)
in Linux should work for the dynamic array
Both are located within malloc.h and both return a size_t
math.log
is the natural logarithm:
math.log(x[, base]) With one argument, return the natural logarithm of x (to base e).
Your equation is therefore:
n = math.log((1 + (FV * r) / p) / math.log(1 + r)))
Note that in your code you convert n to a str
twice which is unnecessary
What works for me was org.mockito.ArgumentMatchers.isA
for example:
isA(long[].class)
that works fine.
the implementation difference of each other is:
public static <T> T any(Class<T> type) {
reportMatcher(new VarArgAware(type, "<any " + type.getCanonicalName() + ">"));
return Primitives.defaultValue(type);
}
public static <T> T isA(Class<T> type) {
reportMatcher(new InstanceOf(type));
return Primitives.defaultValue(type);
}
You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:
if ([category isEqualToString:@"Some String"])
{
// Both strings are equal without respect to their case.
}
Case-insensitive is like this:
if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
// Both strings are equal with respect to their case.
}
Siddharth's answer is nice, but relies on globally-scoped variables. There's a better, more OOP-friendly way.
A UserForm is a class module like any other - the only difference is that it has a hidden VB_PredeclaredId
attribute set to True
, which makes VB create a global-scope object variable named after the class - that's how you can write UserForm1.Show
without creating a new instance of the class.
Step away from this, and treat your form as an object instead - expose Property Get
members and abstract away the form's controls - the calling code doesn't care about controls anyway:
Option Explicit
Private cancelling As Boolean
Public Property Get UserId() As String
UserId = txtUserId.Text
End Property
Public Property Get Password() As String
Password = txtPassword.Text
End Property
Public Property Get IsCancelled() As Boolean
IsCancelled = cancelling
End Property
Private Sub OkButton_Click()
Me.Hide
End Sub
Private Sub CancelButton_Click()
cancelling = True
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
cancelling = True
Cancel = True
Me.Hide
End If
End Sub
Now the calling code can do this (assuming the UserForm was named LoginPrompt
):
With New LoginPrompt
.Show vbModal
If .IsCancelled Then Exit Sub
DoSomething .UserId, .Password
End With
Where DoSomething
would be some procedure that requires the two string parameters:
Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
'work with the parameter values, regardless of where they came from
End Sub
INSERT INTO Table1(Column1,Column2..) SELECT Column1,Column2.. FROM Table2 [WHERE <condition>]
Since the OP was asking for using a custom compare function (and this is what led me to this question as well), I want to give a solid answer here:
Generally, you want to use the built-in sorted()
function which takes a custom comparator as its parameter. We need to pay attention to the fact that in Python 3 the parameter name and semantics have changed.
When providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks):
< 0
) when the left item should be sorted before the right item> 0
) when the left item should be sorted after the right item0
when both the left and the right item have the same weight and should be ordered "equally" without precedenceIn the particular case of the OP's question, the following custom compare function can be used:
def compare(item1, item2):
return fitness(item1) - fitness(item2)
Using the minus operation is a nifty trick because it yields to positive values when the weight of left item1
is bigger than the weight of the right item2
. Hence item1
will be sorted after item2
.
If you want to reverse the sort order, simply reverse the subtraction: return fitness(item2) - fitness(item1)
sorted(mylist, cmp=compare)
or:
sorted(mylist, cmp=lambda item1, item2: fitness(item1) - fitness(item2))
from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(compare))
or:
from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(lambda item1, item2: fitness(item1) - fitness(item2)))
You didn't typed the closingtag from the div with id="infohold.
To answer the question. stringstream
basically allows you to treat a string
object like a stream
, and use all stream
functions and operators on it.
I saw it used mainly for the formatted output/input goodness.
One good example would be c++
implementation of converting number to stream object.
Possible example:
template <class T>
string num2str(const T& num, unsigned int prec = 12) {
string ret;
stringstream ss;
ios_base::fmtflags ff = ss.flags();
ff |= ios_base::floatfield;
ff |= ios_base::fixed;
ss.flags(ff);
ss.precision(prec);
ss << num;
ret = ss.str();
return ret;
};
Maybe it's a bit complicated but it is quite complex. You create stringstream
object ss
, modify its flags, put a number into it with operator<<
, and extract it via str()
. I guess that operator>>
could be used.
Also in this example the string
buffer is hidden and not used explicitly. But it would be too long of a post to write about every possible aspect and use-case.
Note: I probably stole it from someone on SO and refined, but I don't have original author noted.
Try to use it via [ngClass]
property:
<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
(click)="toggle(!isOn)">
Click me!
</div>`,
Below is the Dynamic Script to enable or disable the Triggers.
select 'alter table '+ (select Schema_name(schema_id) from sys.objects o
where o.object_id = parent_id) + '.'+object_name(parent_id) + ' ENABLE TRIGGER '+
Name as EnableScript,*
from sys.triggers t
where is_disabled = 1
Update in 2019:
This is now officially supported in Visual Studio 2019 Preview 2 for .Net Core 3.0 or higher. Of course, you may have to put some thoughts in potential risks of using a Preview version of IDE. I imagine in the near future this will be included in the official Visual Studio.
Fortunately, data breakpoints are no longer a C++ exclusive because they are now available for .NET Core (3.0 or higher) in Visual Studio 2019 Preview 2!
date -j -f "%Y-%m-%d" "2010-10-02" "+%s"
Here is my working solution :
// --------------------------
// SOAP Message creation
// --------------------------
SOAPMessage sm = MessageFactory.newInstance().createMessage();
sm.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
sm.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
SOAPPart sp = sm.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
se.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
se.setAttribute("xmlns:SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/");
se.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
se.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
SOAPBody sb = sm.getSOAPBody();
//
// Add all input fields here ...
//
SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
// -----------------------------------
// URL creation with TimeOut connexion
// -----------------------------------
URL endpoint = new URL(null,
"http://myDomain/myWebService.php",
new URLStreamHandler() { // Anonymous (inline) class
@Override
protected URLConnection openConnection(URL url) throws IOException {
URL clone_url = new URL(url.toString());
HttpURLConnection clone_urlconnection = (HttpURLConnection) clone_url.openConnection();
// TimeOut settings
clone_urlconnection.setConnectTimeout(10000);
clone_urlconnection.setReadTimeout(10000);
return(clone_urlconnection);
}
});
try {
// -----------------
// Send SOAP message
// -----------------
SOAPMessage retour = connection.call(sm, endpoint);
}
catch(Exception e) {
if ((e instanceof com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl) && (e.getCause()!=null) && (e.getCause().getCause()!=null) && (e.getCause().getCause().getCause()!=null)) {
System.err.println("[" + e + "] Error sending SOAP message. Initial error cause = " + e.getCause().getCause().getCause());
}
else {
System.err.println("[" + e + "] Error sending SOAP message.");
}
}
use mode1.name()
or String.valueOf(Modes.mode1)
for python 3.8 version go for anaconda navigator then go for environments --> then go for base(root)----> not installed from drop box--->then search for tensorflow then install it then run the program.......hope it may helpful
Oracle has a page for this issue with SQL and trouble shooting suggestions.
"Troubleshooting Open Cursor Issues" http://docs.oracle.com/cd/E40329_01/admin.1112/e27149/cursor.htm#OMADM5352
If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:
myTimer.Elapsed += PlayMusicEvent;
where
public void PlayMusicEvent(object sender, ElapsedEventArgs e)
{
music.player.Stop();
System.Timers.Timer myTimer = (System.Timers.Timer)sender;
myTimer.Stop();
}
But you need to think about where to store your note.
The .before
argument in dplyr::add_row
can be used to specify the row.
dplyr::add_row(
cars,
speed = 0,
dist = 0,
.before = 3
)
#> speed dist
#> 1 4 2
#> 2 4 10
#> 3 0 0
#> 4 7 4
#> 5 7 22
#> 6 8 16
#> ...
Complementing what people said, remember that the entire string is an array:
$string = "Lorem ipsum lá lá lá";
$string[0] = "B";
echo $string;
"Borem ipsum lá lá lá"
You would basically want something along the lines of:
SELECT e.*, v.Score
FROM Evaluation e
LEFT JOIN Value v
ON v.CaseNum = e.CaseNum AND
v.FileNum = e.FileNum AND
v.ActivityNum = e.ActivityNum;
You can do this by using the following xml
<RelativeLayout
style="@style/GenericProgressBackground"
android:id="@+id/loadingPanel"
>
<ProgressBar
style="@style/GenericProgressIndicator"/>
</RelativeLayout>
With this style
<style name="GenericProgressBackground" parent="android:Theme">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">fill_parent</item>
<item name="android:background">#DD111111</item>
<item name="android:gravity">center</item>
</style>
<style name="GenericProgressIndicator" parent="@android:style/Widget.ProgressBar.Small">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:indeterminate">true</item>
</style>
To use this, you must hide your UI elements by setting the visibility value to GONE and whenever the data is loaded, call setVisibility(View.VISIBLE)
on all your views to restore them. Don't forget to call findViewById(R.id.loadingPanel).setVisiblity(View.GONE)
to hide the loading animation.
If you dont have a loading event/function but just want the loading panel to disappear after x seconds use a Handle to trigger the hiding/showing.
call function on load:
<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">
get video duration
var video = document.getElementById("video");
var duration = video.duration;
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
echo "number of rows: ",$rowcount;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
it is best way (I think) to get the number of special row in mysql with php.
This will work for any resolution,
button{
position:absolute;
bottom: 5%;
right:20%;
}
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
Yes, ng-hide (or ng-show) directive won't create child scope.
Here is my practice:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>
<script>
function main($scope) {
$scope.testa = false;
$scope.testb = false;
$scope.testc = false;
$scope.testd = false;
}
</script>
<div ng-app >
<div ng-controller="main">
Test A: {{testa}}<br />
Test B: {{testb}}<br />
Test C: {{testc}}<br />
Test D: {{testd}}<br />
<div>
testa (without ng-if): <input type="checkbox" ng-model="testa" />
</div>
<div ng-if="!testa">
testb (with ng-if): <input type="checkbox" ng-model="$parent.testb" />
</div>
<div ng-show="!testa">
testc (with ng-show): <input type="checkbox" ng-model="testc" />
</div>
<div ng-hide="testa">
testd (with ng-hide): <input type="checkbox" ng-model="testd" />
</div>
</div>
</div>
Future googlers, on MySQL, try this:
select date_sub(ref_date, interval day(ref_date)-1 day) as day1;
protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), true))
{
_testData.WriteLine(TextBox1.Text); // Write the file.
}
}
Server.MapPath takes a virtual path and returns an absolute one. "~" is used to resolve to the application root.
Following answer can help in this and other similar situations like synchronous AJAX call -
Working example
waitForMe().then(function(intentsArr){
console.log('Finally, I can execute!!!');
},
function(err){
console.log('This is error message.');
})
function waitForMe(){
// Returns promise
console.log('Inside waitForMe');
return new Promise(function(resolve, reject){
if(true){ // Try changing to 'false'
setTimeout(function(){
console.log('waitForMe\'s function succeeded');
resolve();
}, 2500);
}
else{
setTimeout(function(){
console.log('waitForMe\'s else block failed');
resolve();
}, 2500);
}
});
}
Here is an option. This is just for the x coordinates.
var div1Pos = $("#div1").offset();
var div1X = div1Pos.left;
$('#div2').css({left: div1X});
If it worked the way you expected it to (resulting in "abc9"
), what would "9" + 9
deliver? 18
or "99"
?
To remove this ambiguity, you are required to make explicit what you want to convert in this case:
"abc" + str(9)
Eclipse is launching your application with whatever JRE you defined in your launch configuration. Since you're running the 32-bit Eclipse, you're running/debugging against its 32-bit SWT libraries, and you'll need to run a 32-bit JRE.
Your 64-bit JRE is, for whatever reason, your default Installed JRE.
To change this, first make sure you have a 32-bit JRE configured in the Installed JREs preference. Go to Window -> Preferences and navigate to Java -> Installed JREs:
You can click Add and navigate to your 32-bit JVM's JAVA_HOME
to add it.
Then in your Run Configuration, find your Eclipse Application and make sure the Runtime JRE is set to the 32-bit JRE you just configured:
(Note the combobox that is poorly highlighted.)
Don't try replacing SWT jars, that will likely end poorly.
new JwtSecurityTokenHandler().ReadToken("")
will return a SecurityToken
new JwtSecurityTokenHandler().ReadJwtToken("")
will return a JwtSecurityToken
If you just change the method you are using you can avoid the cast in the above answer
You can fix this easily with jQuery - and a little ugly hack :-)
I have a asp.net page with a ReportViewer user control.
<rsweb:ReportViewer ID="ReportViewer1" runat="server"...
In the document ready event I then start a timer and look for the element which needs the overflow fix (as previous posts):
<script type="text/javascript">
$(function () {
// Bug-fix on Chrome and Safari etc (webkit)
if ($.browser.webkit) {
// Start timer to make sure overflow is set to visible
setInterval(function () {
var div = $('#<%=ReportViewer1.ClientID %>_fixedTable > tbody > tr:last > td:last > div')
div.css('overflow', 'visible');
}, 1000);
}
});
</script>
Better than assuming it has a certain id. You can adjust the timer to whatever you like. I set it to 1000 ms here.
First ensure that hlsearch is enabled by issuing the following command
:set hlsearch
You can also add this to your .vimrc file as set
set hlsearch
now when you use the quick search mechanism in command mode or a regular search command, all results will be highlighted. To move forward between results, press 'n' to move backwards press 'N'
In normal mode, to perform a quick search for the word under the cursor and to jump to the next occurrence in one command press '*', you can also search for the word under the cursor and move to the previous occurrence by pressing '#'
In normal mode, quick search can also be invoked with the
/searchterm<Enter>
to remove highlights on ocuurences use, I have bound this to a shortcut in my .vimrc
:nohl
Note : This answer is now out-of-date. You are now required to have an API key to use google maps. Read More
you need to change your API from V2 to V3, Since Google Map Version 3 don't required API Key
Check this out..
write your script
as
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
public class BOX
{
double height, length, breadth;
public static bool operator == (BOX b1, BOX b2)
{
if (b1 is null)
return b2 is null;
return b1.Equals(b2);
}
public static bool operator != (BOX b1, BOX b2)
{
return !(b1 == b2);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
return obj is BOX b2? (length == b2.length &&
breadth == b2.breadth &&
height == b2.height): false;
}
public override int GetHashCode()
{
return (height,length,breadth).GetHashCode();
}
}
Steps that you should follow if you want the thread dump of your StandAlone Java Process
Step 1: Get the Process ID for the shell script calling the java program
linux$ ps -aef | grep "runABCD"
user1 **8535** 4369 0 Mar 25 ? 0:00 /bin/csh /home/user1/runABCD.sh
user1 17796 17372 0 08:15:41 pts/49 0:00 grep runABCD
Step 2: Get the Process ID for the Child which was Invoked by the runABCD. Use the above PID to get the childs.
linux$ ps -aef | grep **8535**
user1 **8536** 8535 0 Mar 25 ? 126:38 /apps/java/jdk/sun4/SunOS5/1.6.0_16/bin/java -cp /home/user1/XYZServer
user1 8535 4369 0 Mar 25 ? 0:00 /bin/csh /home/user1/runABCD.sh
user1 17977 17372 0 08:15:49 pts/49 0:00 grep 8535
Step 3: Get the JSTACK for the particular process. Get the Process id of your XYSServer process. i.e. 8536
linux$ jstack **8536** > threadDump.log
The easy way to change version is first to check your available version using nvm ls then select version from the list nvm use version
Installing the "security" package extras for requests
solved for me:
sudo apt-get install libffi-dev
sudo pip install -U requests[security]
You just need to do it in correct syntax. Let me give you a minimal example I just did with Python interactive shell:
>>> class MyNameClass():
... def __init__(self, myname):
... print myname
...
>>> p1 = MyNameClass('John')
John
As a complement to other's answers, it's possible to desaturate an image half the way on FF without SVG's matrix's headaches:
<feColorMatrix type="saturate" values="$v" />
Where $v
is between 0
and 1
. It's equivalent to filter:grayscale(50%);
.
Live example:
.desaturate {_x000D_
filter: url("#desaturate");_x000D_
-webkit-filter: grayscale(50%);_x000D_
}_x000D_
figcaption{_x000D_
background: rgba(55, 55, 136, 1);_x000D_
padding: 4px 98px 0 18px;_x000D_
color: white;_x000D_
display: inline-block;_x000D_
border-top-left-radius: 8px;_x000D_
border-top-right-radius: 100%;_x000D_
font-family: "Helvetica";_x000D_
}
_x000D_
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
<filter id="desaturate">_x000D_
<feColorMatrix type="saturate" values="0.4"/>_x000D_
</filter>_x000D_
</svg>_x000D_
_x000D_
<figure>_x000D_
<figcaption>Original</figcaption>_x000D_
<img src="http://www.placecage.com/c/500/200"/>_x000D_
</figure>_x000D_
<figure>_x000D_
<figcaption>Half grayed</figcaption>_x000D_
<img class="desaturate" src="http://www.placecage.com/c/500/200"/>_x000D_
</figure>
_x000D_
If is a package then you can get the source for that with:
select text from all_source where name = 'PADCAMPAIGN'
and type = 'PACKAGE BODY'
order by line;
Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.
Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use
select text from all_source where name = 'pAdCampaign'
and type = 'PACKAGE BODY'
order by line;
You can like this:
#{requestScope["paramName"]} ,#{sessionScope["paramName"]}
Because requestScope
or sessionScope
is a Map object.
People have suggested using INetAddress.isReachable. The problem is that some sites configure their firewalls to block ICMP Ping messages. So a "ping" might fail even though the web service is accessible.
And of course, the reverse is true as well. A host may respond to a ping even though the webserver is down.
And of course, a machine may be unable to connect directly to certain (or all) web servers due to local firewall restrictions.
The fundamental problem is that "can connect to the internet" is an ill-defined question, and this kind of thing is difficult to test without:
So generally, the simplest solution is for an app to just try to access whatever it needs to access, and fall back on human intelligence to do the diagnosis.
Anyone mentioned Jshon or JSON.sh?
https://github.com/keenerd/jshon
pipe json to it, and it traverses the json objects and prints out the path to the current object (as a JSON array) and then the object, without whitespace.
http://kmkeen.com/jshon/
Jshon loads json text from stdin, performs actions, then displays the last action on stdout and also was made to be part of the usual text processing pipeline.
Following up on the answer and link from AlexMart, something like this works:
.controller('MyCtrl', function($scope) {
$scope.$on('$ionicView.enter', function() {
// Code you want executed every time view is opened
console.log('Opened!')
})
})
as @chepner says in his comment you are comparing $i to a fixed string.
To expand and rectify the situation you should use [[ ]] with the regex operator =~
eg:
for i in $(ls);do
if [[ $i =~ .*\.java$ ]];then
echo "I want to do something with the file $i"
fi
done
the regex to the right of =~ is tested against the value of the left hand operator and should not be quoted, ( quoted will not error but will compare against a fixed string and so will most likely fail"
but @chepner 's answer above using glob is a much more efficient mechanism.
Display:flex apply flex layout to the flex items or children of the container only. So, the container itself stays a block level element and thus takes up the entire width of the screen.
This causes every flex container to move to a new line on the screen.
Display:inline-flex apply flex layout to the flex items or children as well as to the container itself. As a result the container behaves as an inline flex element just like the children do and thus takes up the width required by its items/children only and not the entire width of the screen.
This causes two or more flex containers one after another, displayed as inline-flex, align themselves side by side on the screen until the whole width of the screen is taken.
To build and install modern Git on CentOS 6:
yum install -y curl-devel expat-devel gettext-devel openssl-devel zlib-devel gcc perl-ExtUtils-MakeMaker
export GIT_VERSION=2.6.4
mkdir /root/git
cd /root/git
wget "https://www.kernel.org/pub/software/scm/git/git-${GIT_VERSION}.tar.gz"
tar xvzf "git-${GIT_VERSION}.tar.gz"
cd git-${GIT_VERSION}
make prefix=/usr/local all
make prefix=/usr/local install
yum remove -y git
git --version # should be GIT_VERSION
you can use like this
private dynamic defaultReminder => reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
Just recently I forked a current Github project called "RibbonMenu" and edited it to fit my needs:
https://github.com/jaredsburrows/RibbonMenu
ActionBar with Menu out
ActionBar with Menu out and search selected
I was scratching my head, not being able to get John Sansom's Join syntax work, at least in MySQL 5.5.30 InnoDB
.
It turns out that this doesn't work.
UPDATE A
SET A.x = 1
FROM A INNER JOIN B
ON A.name = B.name
WHERE A.x <> B.x
But this works:
UPDATE A INNER JOIN B
ON A.name = B.name
SET A.x = 1
WHERE A.x <> B.x
The modulo operator %
in C and C++ is defined for two integers, however, there is an fmod()
function available for usage with doubles.
I also have faced the same issue. Initially tried modifying System PATH which does not worked out. Later resolved by installing Micro Visual Studio express.
I too needed a rounded ImageView, I used the below code, you can modify it accordingly:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth();
@SuppressWarnings("unused")
int h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
By default they are stored here:
%commonprogramfiles%/Microsoft Shared/web server extensions/12/Logs
Using %commonprogramfiles% make it works in non-english systems.
EDIT: According to the comments on the original post this is a C# question.
Short answer: yes, using the this
keyword.
Long answer: yes, using the this
keyword, and here's an example.
class MyClass
{
private object someData;
public MyClass(object data)
{
this.someData = data;
}
public MyClass() : this(new object())
{
// Calls the previous constructor with a new object,
// setting someData to that object
}
}
Place it inside another div, use CSS to move the button to the middle:
<div style="width:100%;height:100%;position:absolute;vertical-align:middle;text-align:center;">
<button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%">
mybuttonname</button>
</div>?
Here is an example: JsFiddle
<div style="position: relative; width:600px;">_x000D_
<p>Content of unknown length</p>_x000D_
<div>Content of unknown height</div>_x000D_
<div id="spacer" style="width: 200px; height: 100px; float:left; display:inline-block"></div>_x000D_
<div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px;"></div>_x000D_
</div>
_x000D_
This should be a comment but I don't have enough reputation yet. The solution works, but visual studio code told me the following putting it into a css sheet:
inline-block is ignored due to the float. If 'float' has a value other than 'none', the box is floated and 'display' is treated as 'block'
So I did it like this
.spacer {
float: left;
height: 20px;
width: 200px;
}
And it works just as well.
The datatype in the same columns name must be equals.
dataTable1.Merge(dataTable2);
After that the result is:
dataTable1 = dataTable1 + dataTable2
I suggest to approximate locally the Earth surface as a sphere with radius given by the WGS84 ellipsoid at the given latitude. I suspect that the exact computation of latMin and latMax would require elliptic functions and would not yield an appreciable increase in accuracy (WGS84 is itself an approximation).
My implementation follows (It's written in Python; I have not tested it):
# degrees to radians
def deg2rad(degrees):
return math.pi*degrees/180.0
# radians to degrees
def rad2deg(radians):
return 180.0*radians/math.pi
# Semi-axes of WGS-84 geoidal reference
WGS84_a = 6378137.0 # Major semiaxis [m]
WGS84_b = 6356752.3 # Minor semiaxis [m]
# Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]
def WGS84EarthRadius(lat):
# http://en.wikipedia.org/wiki/Earth_radius
An = WGS84_a*WGS84_a * math.cos(lat)
Bn = WGS84_b*WGS84_b * math.sin(lat)
Ad = WGS84_a * math.cos(lat)
Bd = WGS84_b * math.sin(lat)
return math.sqrt( (An*An + Bn*Bn)/(Ad*Ad + Bd*Bd) )
# Bounding box surrounding the point at given coordinates,
# assuming local approximation of Earth surface as a sphere
# of radius given by WGS84
def boundingBox(latitudeInDegrees, longitudeInDegrees, halfSideInKm):
lat = deg2rad(latitudeInDegrees)
lon = deg2rad(longitudeInDegrees)
halfSide = 1000*halfSideInKm
# Radius of Earth at given latitude
radius = WGS84EarthRadius(lat)
# Radius of the parallel at given latitude
pradius = radius*math.cos(lat)
latMin = lat - halfSide/radius
latMax = lat + halfSide/radius
lonMin = lon - halfSide/pradius
lonMax = lon + halfSide/pradius
return (rad2deg(latMin), rad2deg(lonMin), rad2deg(latMax), rad2deg(lonMax))
EDIT: The following code converts (degrees, primes, seconds) to degrees + fractions of a degree, and vice versa (not tested):
def dps2deg(degrees, primes, seconds):
return degrees + primes/60.0 + seconds/3600.0
def deg2dps(degrees):
intdeg = math.floor(degrees)
primes = (degrees - intdeg)*60.0
intpri = math.floor(primes)
seconds = (primes - intpri)*60.0
intsec = round(seconds)
return (int(intdeg), int(intpri), int(intsec))
Use this code using v4
ExampleFragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
VAR=value
sets VAR to value.
After that export VAR
will give it to child processes too.
export VAR=value
is a shorthand doing both.
npm
decided to add a new command:
npm fund
that will provide more visibility to npm users on what dependencies are actively looking for ways to fund their work.
npm install
will also show a single message at the end in order to let user aware that dependencies are looking for funding, it looks like this:
$ npm install
packages are looking for funding.
run `npm fund` for details.
Running npm fund <package>
will open the url listed for that given package right in your browser.
To get a meaningful/useful view of the two tables, you normally need to determine an identifying field from each table that can then be used in the ON clause in a JOIN.
THen in your view:
SELECT T1.*, T2.* FROM T1 JOIN T2 ON T1.IDFIELD1 = T2.IDFIELD2
You mention no fields are "common", but although the identifying fields may not have the same name or even be the same data type, you could use the convert / cast functions to join them in some way.
A moving average is a convolution, and numpy will be faster than most pure python operations. This will give you the 10 point moving average.
import numpy as np
smoothed = np.convolve(data, np.ones(10)/10)
I would also strongly suggest using the great pandas package if you are working with timeseries data. There are some nice moving average operations built in.
// Dialog box
public void dialogBox() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Click on Image for tag");
alertDialogBuilder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
alertDialogBuilder.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
You are trying to assign an array to ngClass, but the syntax for the array elements is wrong since you separate them with a ||
instead of a ,
.
Try this:
<section [ngClass]="[menu1 ? 'class1' : '', menu2 ? 'class1' : '', (something && (menu1 || menu2)) ? 'class2' : '']">
This other option should also work:
<section [ngClass.class1]="menu1 || menu2" [ngClass.class2] = "(menu1 || menu2) && something">
This is the best help that I found:
https://atom.io/packages/atom-beautify
This package can be installed in Atom and then CTRL+ALT+B solve the problem.
Why not have the item_1, item_2, etc. IDs on the article tags themselves? Like this:
<article id="item_1">
...
</article>
<article id="item_2">
...
</article>
...
It seems unnecessary to add the wrapper divs. ID values have no semantic meaning in HTML, so I think it would be perfectly valid to do this - you're not saying that the first article is always item_1, just item_1 within the context of the current page. IDs are not required to have any meaning that is independent of context.
Also, as to your question on line 26, I don't think the <header> tag is required there, and I think you could omit it since it's on its own in the "main-left" div. If it were in the main list of articles you might want to include the <header> tag just for the sake of consistency.
I've finally managed to do it. Answer in code snippet below:
var querystring = require('querystring');
var request = require('request');
var form = {
username: 'usr',
password: 'pwd',
opaque: 'opaque',
logintype: '1'
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'http://myUrl',
body: formData,
method: 'POST'
}, function (err, res, body) {
//it works!
});
New answer to old question, sorry. I thought I'd add my $.02
The OP asked if the headers were encrypted.
They are: in transit.
They are NOT: when not in transit.
So, your browser's URL (and title, in some cases) can display the querystring (which usually contain the most sensitive details) and some details in the header; the browser knows some header information (content type, unicode, etc); and browser history, password management, favorites/bookmarks, and cached pages will all contain the querystring. Server logs on the remote end can also contain querystring as well as some content details.
Also, the URL isn't always secure: the domain, protocol, and port are visible - otherwise routers don't know where to send your requests.
Also, if you've got an HTTP proxy, the proxy server knows the address, usually they don't know the full querystring.
So if the data is moving, it's generally protected. If it's not in transit, it's not encrypted.
Not to nit pick, but data at the end is also decrypted, and can be parsed, read, saved, forwarded, or discarded at will. And, malware at either end can take snapshots of data entering (or exiting) the SSL protocol - such as (bad) Javascript inside a page inside HTTPS which can surreptitiously make http (or https) calls to logging websites (since access to local harddrive is often restricted and not useful).
Also, cookies are not encrypted under the HTTPS protocol, either. Developers wanting to store sensitive data in cookies (or anywhere else for that matter) need to use their own encryption mechanism.
As to cache, most modern browsers won't cache HTTPS pages, but that fact is not defined by the HTTPS protocol, it is entirely dependent on the developer of a browser to be sure not to cache pages received through HTTPS.
So if you're worried about packet sniffing, you're probably okay. But if you're worried about malware or someone poking through your history, bookmarks, cookies, or cache, you are not out of the water yet.
Click on the WAMP server icon and from the menu under Config Files select httpd.conf. A long text file will open up in notepad. In this file scroll down to the line that reads Port 80 and change this to read Port 8080, Save the file and close notepad. Once again click on the wamp server icon and select restart all services. One more change needs to be made before we are done. In Windows Explorer find the location where WAMP server was installed which is by Default C:\Wamp.
There's no practical difference. Just use the relationship which makes the most sense given the way you see your problem as Devendra illustrated.
Excerpt from http://www.mingw.org/wiki/FAQ:
What's the difference between make and mingw32-make?
The "native" (i.e.: MSVCRT dependent) port of make is lacking in some functionality and has modified functionality due to the lack of POSIX on Win32. There also exists a version of make in the MSYS distribution that is dependent on the MSYS runtime. This port operates more as make was intended to operate and gives less headaches during execution. Based on this, the MinGW developers/maintainers/packagers decided it would be best to rename the native version so that both the "native" version and the MSYS version could be present at the same time without file name collision.
So,look into C:\MinGW\bin directory and first make sure what make executable, have you installed.(make.exe or mingw32-make.exe)
Before using MinGW, you should add C:\MinGW\bin; to the PATH environment variable using the instructions mentioned at http://www.mingw.org/wiki/Getting_Started/
Then cd to your directory, where you have the makefile and Try using mingw32-make.exe makefile.in
or simply make.exe makefile.in
(depending on executables in C:\MinGW\bin).
If you want a GUI based solution, install DevCPP IDE and then re-make.
ALTER DATABASE name OWNER TO new_owner;
See the Postgresql manual's entry on this for more details.
Solution for @umounted answer, because that broke with a one-element tuple, since (1,) is not valid SQL.:
>>> random_ids = [1234,123,54,56,57,58,78,91]
>>> cursor.execute("create table test (id)")
>>> for item in random_ids:
cursor.execute("insert into test values (%d)" % item)
>>> sublist = [56,57,58]
>>> cursor.execute("select id from test where id in %s" % str(tuple(sublist)).replace(',)',')'))
>>> a = cursor.fetchall()
>>> a
[(56,), (57,), (58,)]
Other solution for sql string:
cursor.execute("select id from test where id in (%s)" % ('"'+'", "'.join(l)+'"'))
I would pick "default" for data type of variable (null
for strings/objects, 0
for numbers), but indeed check what code that will consume the object expects. Don't forget there there is sometimes distinction between null
/default vs. "not present".
Check out null object pattern - sometimes it is better to pass some special object instead of null
(i.e. []
array instead of null
for arrays or ""
for strings).
use "Content-type: application/x-www-form-urlencoded" instead of "application/json"
If you only have as "click event handler", use a <button>
instead. A link has a specific semantic meaning.
E.g.:
<button onclick="ShowOld(2367,146986,2)">
<img title="next page" alt="next page" src="/themes/me/img/arrn.png">
</button>
As already pointed out, b += 1
updates b
in-place, while a = a + 1
computes a + 1
and then assigns the name a
to the result (now a
does not refer to a row of A
anymore).
To understand the +=
operator properly though, we need also to understand the concept of mutable versus immutable objects. Consider what happens when we leave out the .reshape
:
C = np.arange(12)
for c in C:
c += 1
print(C) # [ 0 1 2 3 4 5 6 7 8 9 10 11]
We see that C
is not updated, meaning that c += 1
and c = c + 1
are equivalent. This is because now C
is a 1D array (C.ndim == 1
), and so when iterating over C
, each integer element is pulled out and assigned to c
.
Now in Python, integers are immutable, meaning that in-place updates are not allowed, effectively transforming c += 1
into c = c + 1
, where c
now refers to a new integer, not coupled to C
in any way. When you loop over the reshaped arrays, whole rows (np.ndarray
's) are assigned to b
(and a
) at a time, which are mutable objects, meaning that you are allowed to stick in new integers at will, which happens when you do a += 1
.
It should be mentioned that though +
and +=
are meant to be related as described above (and very much usually are), any type can implement them any way it wants by defining the __add__
and __iadd__
methods, respectively.
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
Add a reference to the Microsoft.VisualBasic (yes, it says VisualBasic but it works in C# just as well - remember that at the end it is all just IL).
Use the Microsoft.VisualBasic.FileIO.TextFieldParser
class to parse CSV file Here is the sample code:
Dim parser As TextFieldParser = New TextFieldParser("C:\mar0112.csv")
parser.TextFieldType = FieldType.Delimited
parser.SetDelimiters(",")
While Not parser.EndOfData
'Processing row
Dim fields() As String = parser.ReadFields
For Each field As String In fields
'TODO: Process field
Next
parser.Close()
End While
The problem with IIF(Fields!column.Value = "Approved", "Green") is that you are missing the third parameter. The correct syntax is IIF( [some boolean expression], [result if boolean expression is true], [result if boolean is false])
Try this
=IIF(Fields!Column.Value = "Approved", "Green", "No Color")
Here is a list of expression examples Expression Examples in Reporting Services
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.
Remember that your img is not really a DOM element but a javascript expression.
This is a JSX attribute expression. Put curly braces around the src string expression and it will work. See http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions
In javascript, the class attribute is reference using className. See the note in this section: http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components
/** @jsx React.DOM */
var Hello = React.createClass({
render: function() {
return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>;
}
});
React.renderComponent(<Hello name="World" />, document.body);
Shorter version of Andrew Marc Newton's comprehensive answer above. This one does not check the status code for success, which you should do to avoid undefined UI behaviour.
This one was for an annoying system where I could guarantee jQuery but no other includes, so I wanted a technique short enough to not be farmed off into an external script if forced into it. (You could make it even shorter by passing the index 0 to the first "recursive" call but force of style habits made me add the sugar).
I'm also assigning the dependency list to a module name, so this block can be included anywhere you need "module1" and the scripts and dependent initialization will only be included/run once (you can log index
in the callback and see a single ordered set of AJAX requests runnning)
if(typeof(__loaders) == 'undefined') __loaders = {};
if(typeof(__loaders.module1) == 'undefined')
{
__loaders.module1 = false;
var dependencies = [];
dependencies.push('/scripts/loadmefirst.js');
dependencies.push('/scripts/loadmenext.js');
dependencies.push('/scripts/loadmelast.js');
var getScriptChain = function(chain, index)
{
if(typeof(index) == 'undefined')
index = 0;
$.getScript(chain[index],
function()
{
if(index == chain.length - 1)
{
__loaders.module1 = true;
/* !!!
Do your initialization of dependent stuff here
!!! */
}
else
getScriptChain(chain, index + 1);
}
);
};
getScriptChain(dependencies);
}
You still need two INSERT
statements, but it sounds like you want to get the IDENTITY
from the first insert and use it in the second, in which case, you might want to look into OUTPUT
or OUTPUT INTO
: http://msdn.microsoft.com/en-us/library/ms177564.aspx
For secure and change root for docker container an docker host try use --uidmap
and --private-uids
options
https://github.com/docker/docker/pull/4572#issuecomment-38400893
Also you may remove several capabilities (--cap-drop
) in docker container for security
http://opensource.com/business/14/9/security-for-docker
UPDATE support should come in docker > 1.7.0
UPDATE Version 1.10.0
(2016-02-04) add --userns-remap
flag
https://github.com/docker/docker/blob/master/CHANGELOG.md#security-2
For me I had a AdoptOpenJDK 8 installed, instead of SE JDK 8. For which it was not able to recognize JAVA_HOME or mvn commands.
Check your java_home
/usr/libexec/java_home -V
and use JAVA SE SDK if it is different.
Then follow the above steps to install maven and check again
For ones who wanna use scikit-learn, you can use
from sklearn.preprocessing import normalize
x = [1,2,3,4]
normalize([x]) # array([[0.18257419, 0.36514837, 0.54772256, 0.73029674]])
normalize([x], norm="l1") # array([[0.1, 0.2, 0.3, 0.4]])
normalize([x], norm="max") # array([[0.25, 0.5 , 0.75, 1.]])
There is a Spark JIRA, SPARK-7481, open as of today, oct 20, 2016, to add a spark-cloud module which includes transitive dependencies on everything s3a and azure wasb: need, along with tests.
And a Spark PR to match. This is how I get s3a support into my spark builds
If you do it by hand, you must get hadoop-aws JAR of the exact version the rest of your hadoop JARS have, and a version of the AWS JARs 100% in sync with what Hadoop aws was compiled against. For Hadoop 2.7.{1, 2, 3, ...}
hadoop-aws-2.7.x.jar
aws-java-sdk-1.7.4.jar
joda-time-2.9.3.jar
+ jackson-*-2.6.5.jar
Stick all of these into SPARK_HOME/jars
. Run spark with your credentials set up in Env vars or in spark-default.conf
the simplest test is can you do a line count of a CSV File
val landsatCSV = "s3a://landsat-pds/scene_list.gz"
val lines = sc.textFile(landsatCSV)
val lineCount = lines.count()
Get a number: all is well. Get a stack trace. Bad news.
out and ref are exactly the same with the exception that out variables don't have to be initialized before sending it into the abyss. I'm not that smart, I cribbed that from the MSDN library :).
To be more explicit about their use, however, the meaning of the modifier is that if you change the reference of that variable in your code, out and ref will cause your calling variable to change reference as well. In the code below, the ceo variable will be a reference to the newGuy once it returns from the call to doStuff. If it weren't for ref (or out) the reference wouldn't be changed.
private void newEmployee()
{
Person ceo = Person.FindCEO();
doStuff(ref ceo);
}
private void doStuff(ref Person employee)
{
Person newGuy = new Person();
employee = newGuy;
}
To find a very long list of words in big files, it can be more efficient to use egrep:
remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B
mail -s "$(echo -e "This is the subject\nFrom: Paula <[email protected]>\n
Reply-to: [email protected]\nContent-Type: text/html\n")"
[email protected] < htmlFileMessage.txt
the above is my solution..just replace the "Paula" with any name you want e.g Johny Bravo..any extra headers can be added just after the from and before the reply to...just make sure you know your headers syntax before adding them....this worked perfectly for me.
Here's a solution with nested list comprehensions, os.walk
and simple suffix matching instead of glob
:
import os
cfiles = [os.path.join(root, filename)
for root, dirnames, filenames in os.walk('src')
for filename in filenames if filename.endswith('.c')]
It can be compressed to a one-liner:
import os;cfiles=[os.path.join(r,f) for r,d,fs in os.walk('src') for f in fs if f.endswith('.c')]
or generalized as a function:
import os
def recursive_glob(rootdir='.', suffix=''):
return [os.path.join(looproot, filename)
for looproot, _, filenames in os.walk(rootdir)
for filename in filenames if filename.endswith(suffix)]
cfiles = recursive_glob('src', '.c')
If you do need full glob
style patterns, you can follow Alex's and
Bruno's example and use fnmatch
:
import fnmatch
import os
def recursive_glob(rootdir='.', pattern='*'):
return [os.path.join(looproot, filename)
for looproot, _, filenames in os.walk(rootdir)
for filename in filenames
if fnmatch.fnmatch(filename, pattern)]
cfiles = recursive_glob('src', '*.c')
I got this answer from here. and its works for me
Require local
Change to
Require all granted
Order Deny,Allow
Allow from all
Answer by @Calvin Froedge is the shortest answer but have an issue also mentioned by @kizu. Due to inconsistent width of the div the div will flick on hover. To solve this issue add minus margin to the right on hover
#div {
overflow:hidden;
height:whatever px;
}
#div:hover {
overflow-y:scroll;
margin-right: -15px; // adjust according to scrollbar width
}
import re
mylist = [x for x in re.compile('\s*[,|\s+]\s*').split(string)]
Simply, comma or at least one white spaces with/without preceding/succeeding white spaces.
Please try!
You're "setting" the value of that variable/attribute. Not overriding or overloading it. Your code is very, very common and normal.
All of these terms ("set", "override", "overload") have specific meanings. Override and Overload are about polymorphism (subclassing).
From http://en.wikipedia.org/wiki/Object-oriented_programming :
Polymorphism allows the programmer to treat derived class members just like their parent class' members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as "+", to perform several different functions depending on the implementation. The "+" operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the addition operator, "+", to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism.
This is the easiest script to test.
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>
<script language="C#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("From email account");
mail.To.Add("To email account");
//set the content
mail.Subject = "This is a test email from C# script";
mail.Body = "This is a test email from C# script";
//send the message
SmtpClient smtp = new SmtpClient("mail.domainname.com");
NetworkCredential Credentials = new NetworkCredential("to email account", "Password");
smtp.Credentials = Credentials;
smtp.Send(mail);
lblMessage.Text = "Mail Sent";
}
</script>
<html>
<body>
<form runat="server">
<asp:Label id="lblMessage" runat="server"></asp:Label>
</form>
</body>
or in a better way we can have like this
Let's say your primary key is an Integer and object you save is "ticket", then you can get it like this. When you save the object, id is always returned
//unboxing will occur here so that id here will be value type not the reference type. Now you can check id for 0 in case of save failure. like below:
int id = (Integer) session.save(ticket);
if(id==0)
your session.save call was not success.
else '
your call to session.save was successful.
make sure you don't have env variable NODE_ENV
set to 'production'.
If you do, dev dependencies will not be installed without the --dev
flag
If you are using Fish shell, you can leverage the string
functions:
git branch -d (git branch -l "<your pattern>" | string trim)
This is not much different from the Powershell options in some of the other answers.
#!/bin/bash
# Target directory
TARGET=/target/directory/here
for i in $(git diff --name-only)
do
# First create the target directory, if it doesn't exist.
mkdir -p "$TARGET/$(dirname $i)"
# Then copy over the file.
cp -rf "$i" "$TARGET/$i"
done
https://stackoverflow.com/users/79061/sebastian-paaske-t%c3%b8rholm
You can use the function int atoi (const char * str);
.
You need to include #include <stdlib.h>
and use the function in this way:int x = atoi(argv[1]);
Here more information if needed: atoi - C++ Reference
Use:
awk -v FS='\t' -v OFS='\t' ...
Example from one of my scripts.
I use the FS
and OFS
variables to manipulate BIND zone files, which are tab delimited:
awk -v FS='\t' -v OFS='\t' \
-v record_type=$record_type \
-v hostname=$hostname \
-v ip_address=$ip_address '
$1==hostname && $3==record_type {$4=ip_address}
{print}
' $zone_file > $temp
This is a clean and easy to read way to do this.
Taking a guess at what it is you're asking for. I'm assuming by millisecond frame timer you're looking for something that acts like the following,
double mticks()
{
struct timeval tv;
gettimeofday(&tv, 0);
return (double) tv.tv_usec / 1000 + tv.tv_sec * 1000;
}
but uses std::chrono
instead,
double mticks()
{
typedef std::chrono::high_resolution_clock clock;
typedef std::chrono::duration<float, std::milli> duration;
static clock::time_point start = clock::now();
duration elapsed = clock::now() - start;
return elapsed.count();
}
Hope this helps.
The XLSB format is also dedicated to the macros embeded in an hidden workbook file located in excel startup folder (XLSTART).
A quick & dirty test with a xlsm or xlsb in XLSTART folder:
Measure-Command { $x = New-Object -com Excel.Application ;$x.Visible = $True ; $x.Quit() }
0,89s with a xlsb (binary) versus 1,3s with the same content in xlsm format (xml in a zip file) ... :)
You could also use Rails' with_indifferent_access
method so you could access the body with either symbols or strings.
value = '{"val":"test","val1":"test1","val2":"test2"}'
json = JSON.parse(value).with_indifferent_access
then
json[:val] #=> "test"
json["val"] #=> "test"
I currently have Xcode 4.6.3 and 5.0 installed. I used the following bash script to link 5.0 to the SDKs in the old version:
platforms_path="$1/Contents/Developer/Platforms";
if [ -d $platforms_path ]; then
for platform in `ls $platforms_path`
do
sudo ln -sf $platforms_path/$platform/Developer/SDKs/* $(xcode-select --print-path)/Platforms/$platform/Developer/SDKs;
done;
fi;
You just need to supply it with the path to the .app:
./xcode.sh /Applications/Xcode-463.app
if((pswd.length<6 || pswd.length>12) || pswd == ""){
document.getElementById("passwordloc").innerHTML="character should be between 6-12 characters"; status=false;
}
else {
if(pswd != pswdcnf) {
document.getElementById("passwordconfirm").innerHTML="password doesnt matched"; status=true;
} else {
document.getElementById("passwordconfirm").innerHTML="password matche";
document.getElementById("passwordloc").innerHTML = '';
}
}
I just rechecked the performance on http://jsperf.com/javascript-concat-vs-join/2. The test-cases concatenate or join the alphabet 1,000 times.
In current browsers (FF, Opera, IE11, Chrome), "concat" is about 4-10 times faster than "join".
In IE8, both return about equal results.
In IE7, "join" is about 100 times faster unfortunately.
The official way to find out if you have 4.5 installed (and not 4.0) is in the registry keys :
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full
Relesae DWORD needs to be bigger than 378675 Here is the Microsoft doc for it
all the other answers of checking the minor version after 4.0.30319.xxxxx seem correct though (msbuild.exe -version , or properties of clr.dll), i just needed something documented (not a blog)
use sth like
<input type="text" name="yourName" placeholder="A new value" />
Here's my little 2 cents, for what it's worth ;)
def indexLines(filename, lines=[2,4,6,8,10,12,3,5,7,1]):
fp = open(filename, "r")
src = fp.readlines()
data = [(index, line) for index, line in enumerate(src) if index in lines]
fp.close()
return data
# Usage below
filename = "C:\\Your\\Path\\And\\Filename.txt"
for line in indexLines(filename): # using default list, specify your own list of lines otherwise
print "Line: %s\nData: %s\n" % (line[0], line[1])
Hej this is a modified version which works OK in FF @least for me and inserts at the carets position
$.fn.extend({
insertAtCaret: function(myValue){
var obj;
if( typeof this[0].name !='undefined' ) obj = this[0];
else obj = this;
if ($.browser.msie) {
obj.focus();
sel = document.selection.createRange();
sel.text = myValue;
obj.focus();
}
else if ($.browser.mozilla || $.browser.webkit) {
var startPos = obj.selectionStart;
var endPos = obj.selectionEnd;
var scrollTop = obj.scrollTop;
obj.value = obj.value.substring(0, startPos)+myValue+obj.value.substring(endPos,obj.value.length);
obj.focus();
obj.selectionStart = startPos + myValue.length;
obj.selectionEnd = startPos + myValue.length;
obj.scrollTop = scrollTop;
} else {
obj.value += myValue;
obj.focus();
}
}
})
Here's a simple function that will downcast floats into the smallest possible integer type that doesn't lose any information. For examples,
100.0 can be converted from float to integer, but 99.9 can't (without losing information to rounding or truncation)
Additionally, 1.0 can be downcast all the way to int8
without losing information, but the smallest integer type for 100_000.0 is int32
Code examples:
import numpy as np
import pandas as pd
def float_to_int( s ):
if ( s.astype(np.int64) == s ).all():
return pd.to_numeric( s, downcast='integer' )
else:
return s
# small integers are downcast into 8-bit integers
float_to_int( np.array([1.0,2.0]) )
Out[1]:array([1, 2], dtype=int8)
# larger integers are downcast into larger integer types
float_to_int( np.array([100_000.,200_000.]) )
Out[2]: array([100000, 200000], dtype=int32)
# if there are values to the right of the decimal
# point, no conversion is made
float_to_int( np.array([1.1,2.2]) )
Out[3]: array([ 1.1, 2.2])
<?php
header('Content-type: text/plain');
header('Content-Disposition: attachment;
filename="<name for the created file>"');
/*
assign file content to a PHP Variable $content
*/
echo $content;
?>
A short way to LabelEncoder()
multiple columns with a dict()
:
from sklearn.preprocessing import LabelEncoder
le_dict = {col: LabelEncoder() for col in columns }
for col in columns:
le_dict[col].fit_transform(df[col])
and you can use this le_dict
to labelEncode any other column:
le_dict[col].transform(df_another[col])
this is because str is pointing to a string literal means a constant string ...but you are trying to modify it by copying . Note : if it would have been an error due to memory allocation it would have been given segmentation fault at the run time .But this error is coming due to constant string modification or you can go through the below for more details abt bus error :
Bus errors are rare nowadays on x86 and occur when your processor cannot even attempt the memory access requested, typically:
Segmentation faults occur when accessing memory which does not belong to your process, they are very common and are typically the result of:
To be more precise this is not manipulating the pointer itself that will cause issues, it's accessing the memory it points to (dereferencing).
This happen to me after upgrade eclipse version. What works for me was clean the eclipse cache. Go to Window > Preferences > Network Connection > Cache > Remove All.
I hope this works for anyone!
This is a simple way to access a component's methods from other component
// This is external shared (reusable) component, so you can call its methods from other components
export default {
name: 'SharedBase',
methods: {
fetchLocalData: function(module, page){
// .....fetches some data
return { jsonData }
}
}
}
// This is your component where you can call SharedBased component's method(s)
import SharedBase from '[your path to component]';
var sections = [];
export default {
name: 'History',
created: function(){
this.sections = SharedBase.methods['fetchLocalData']('intro', 'history');
}
}
There is no need to use angular http, you can get with js native functions
// you will ned this function to fetch the image blob._x000D_
async function getImage(url, fileName) {_x000D_
// on the first then you will return blob from response_x000D_
return await fetch(url).then(r => r.blob())_x000D_
.then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform_x000D_
_x000D_
return new File([blob], fileName+'.'+ blob.type.split('/')[1]) ;_x000D_
});_x000D_
}_x000D_
_x000D_
// example url_x000D_
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';_x000D_
_x000D_
// calling the function_x000D_
getImage(url, 'your-name-image').then(function(file) {_x000D_
_x000D_
// with file reader you will transform the file in a data url file;_x000D_
var reader = new FileReader();_x000D_
reader.readAsDataURL(file);_x000D_
reader.onloadend = () => {_x000D_
_x000D_
// just putting the data url to img element_x000D_
document.querySelector('#image').src = reader.result ;_x000D_
}_x000D_
})
_x000D_
<img src="" id="image"/>
_x000D_
In Oracle :
ALTER TABLE one ADD two_id INTEGER CONSTRAINT Fk_two_id REFERENCES two(id);
This doesn't use TEMP Tables, but real tables instead. If the problem is just about temp tables and not about table creation or dropping tables, this will work:
SELECT DISTINCT * INTO TableA_Verify FROM TableA;
DROP TABLE TableA;
RENAME TABLE TableA_Verify TO TableA;
According to the VueJs 2.0, you should not mutate a prop inside the component. They are only mutated by their parents. Therefore, you should define variables in data with different names and keep them updated by watching actual props. In case the list prop is changed by a parent, you can parse it and assign it to mutableList. Here is a complete solution.
Vue.component('task', {
template: ´<ul>
<li v-for="item in mutableList">
{{item.name}}
</li>
</ul>´,
props: ['list'],
data: function () {
return {
mutableList = JSON.parse(this.list);
}
},
watch:{
list: function(){
this.mutableList = JSON.parse(this.list);
}
}
});
It uses mutableList to render your template, thus you keep your list prop safe in the component.