While adding a AutoRun entry to HKEY_CURRENT_USER\Software\Microsoft\Command Processor
like Shinnok's answer is the way to go it can also really mess things up, you really should try to detect a simple cmd.exe startup vs a script/program using cmd.exe as a child process:
IF /I x"%COMSPEC%"==x%CMDCMDLINE% (cd /D c:\)
there are two types of environment variable first User variable if you path in this it will work for that particular user only. second is System variable if you set path in this it is used by all type of users.. In my system i set JAVA_HOME in system variable,it was not working,then i set path in User variable it is working.....so try in both type of environment variable...
I had a similar problem. Using a freeware utility called Unlocker (version 1.9.2), I found that my antivirus software (Panda free) had left a hanging lock on the executable file even though it didn't detect any threat. Unlocker was able to unlock it.
Following up on Mat's answer (use Cygwin), here are some detailed instructions for : installing gcc on Windows The packages you want are gcc, gdb and make. Cygwin installer lets you install additional packages if you need them.
You can check if the port is being used by other program using WAMP menu -
Click on WAMP icon select Apache -> Service -> Test Port 80
, this will check if the port is used by any other program
Also do this select Apache -> Service -> Install Service
, this will make apache use port 80 if the port is not already used by any other program like IIS or Skype
Restart the WAMP see if the problem is fixed.
If port 80 is already used by some program, then you can choose other listening port for WAMP. To do this -
click WAMP icon -> Apache -> httpd.conf
Now find listen 80
(where 80 is port number, it can be different on your system)
Now change that to something else like 3333, you can access WAMP homepage by typing localhost:3333
or 127.0.0.1:3333
in browser's address bar.
If you want WAMP to use port 80, uninstall the program that is using port 80 and then do things stated in step 2 or you can change port in that program's setting, also check httpd.conf
file for listen [port]
line.
I just tested this extremely simple method and it works perfectly--but I use the built-in Administrator account, so I don't have to jump through hoops for elevated privileges.
The following batch file relieves the user of the need to move files in/out of system folders. It also leaves it up to Windows to apply the proper version of Regsvr32
.
INSTRUCTIONS:
In the folder that contains the library (-.dll
or -.ax
) file you wish to register, open a new text file and paste in ONE of the routines below :
echo BEGIN DRAG-AND-DROP %n1 REGISTRAR FOR 64-BIT SYSTEMS
copy %1 C:\Windows\System32
regsvr32 "%nx1"
echo END BATCH FILE
pause
echo BEGIN DRAG-AND-DROP %n1 REGISTRAR FOR 32-BIT SYSTEMS
copy %1 C:\Windows\SysWOW64
regsvr32 "%nx1"
echo END BATCH FILE
pause
Save your new text file as a batch (-.bat
) file; then simply drag-and-drop your -.dll
or -.ax
file on top of the batch file.
If UAC doesn't give you the opportunity to run the batch file as an Administrator, you may need to manually elevate privileges (instructions are for Windows 7):
Create shortcut
;Properties
;Compatibility
tab;Run this program as administrator
;-.dll
or -.ax
file on top of the new shortcut instead of the batch file.That's it. I chose COPY
instead of MOVE
to prevent the failure of any UAC-related follow-up attempt(s). Successful registration should be followed by deletion of the original library (-.dll
or -.ax
) file.
Don't worry about copies made to the system folder (C:\Windows\System32
or C:\Windows\SysWOW64
) by previous passes--they will be overwritten every time you run the batch file.
Unless you ran the wrong batch file, in which case you will probably want to delete the copy made to the wrong system folder (C:\Windows\System32
or C:\Windows\SysWOW64
) before running the proper batch file, ...or...
Help Windows choose the right library file to register by fully-qualifying its directory location.
C:\Windows\System32
C:\Windows\SysWOW64
%nx1
regsvr32 "C:\Windows\System32\%nx1"
regsvr32 "C:\Windows\SysWOW64\%nx1"
%nx1
from system folder pathRun this shotgun batch file, which will (in order):
C:\Windows\System32
;C:\Windows\System32
;C:\Windows\SystemWOW64
In my case, it was due to an IP address that Apache is listening to. Previously I have set it to 192.168.10.6 and recently Apache service is not running. I noticed that due to My laptop wifi changed recently and new IP is different. After fixing the wifi IP to laptop previous IP, Apache service is running again without any error.
Also if you don't want to change wifi IP then remove/comment that hardcode IP in httpd.conf file to resolve conflict.
Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.
hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost
...and many others...
Usage:
hosts - run hosts command interpreter
hosts <command> <params> - execute hosts command
Commands:
add <host> <aliases> <addr> # <comment> - add new host
set <host|mask> <addr> # <comment> - set ip and comment for host
rem <host|mask> - remove host
on <host|mask> - enable host
off <host|mask> - disable host
view [all] <mask> - display enabled and visible, or all hosts
hide <host|mask> - hide host from 'hosts view'
show <host|mask> - show host in 'hosts view'
print - display raw hosts file
format - format host rows
clean - format and remove all comments
rollback - rollback last operation
backup - backup hosts file
restore - restore hosts file from backup
recreate - empty hosts file
open - open hosts file in notepad
This should solve your problem, you should try to run the following below:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Check which one the system is currently using:
python --version
Add the main folder location (e.g. C/ProgramFiles) and Scripts location (C/ProgramFiles/Scripts) to Environment Variables of the system. Add both 3.x version and 2.x version
Path location is ranked inside environment variable. If you want to use Python 2.x simply put path of python 2.x first, if you want for Python 3.x simply put 3.x first
Please open your Visual Studio as administrator:
Had to try this:
cd
commandjava.exe -jar *filename*.jar
The app should pop right after that.
Go to Run (WINDOWS + R) and Type shell:startup, paste your .bat file there !
Combining and organizing all the current answers into one answer, then adding my own research:
Brief summary of Microsoft gadget development:
What are they written in? Windows Vista/Seven gadgets are developed in a mix of XML, HTML, CSS, and some IE scripting language. It is also possible to use C# with the latest release of Script#.
How are they packaged/deployed? The actual gadgets are stored in *.gadget files, which are simply the text source files listed above compressed into a single zip file.
Useful references for gadget development:
where do I start? Good introductory references to Windows Vista/Seven gadget development:
If you are willing to use offline resources, this book appears to be an excellent resource:
What do I need to know? Some other useful references; not necessarily instructional
Update: Well, this has proven to be a popular answer~ Sharing my own recent experience with Windows 7 gadget development:
Perhaps the easiest way to get started with Windows 7 gadget development is to modify a gadget that has already been developed. I recently did this myself because I wanted a larger clock gadget. Unable to find any, I tinkered with a copy of the standard Windows clock gadget until it was twice as large. I recommend starting with the clock gadget because it is fairly small and well-written. Here is the process I used:
C:\Program Files\Windows Sidebar\Gadgets\Clock.Gadget\
<name>Clock</name>
This is the name that will be displayed in the "Gadgets Gallery" window.%LOCALAPPDATA%\Microsoft\Windows Sidebar\
)I tried the following; it helped me. I hope it help you also.
cd /c/xampp/your-project
If you want to change your 'sa' password with SQL Server Management Studio, here are the steps:
Change server authentication mode - Right click on root, choose Properties, from Security tab select "SQL Server and Windows Authentication mode", click OK
Set sa password - Navigate to Security > Logins > sa, right click on it, choose Properties, from General tab set the Password (don't close the window)
Grant permission - Go to Status tab, make sure the Grant and Enabled radiobuttons are chosen, click OK
Restart SQLEXPRESS service from your local services (Window+R > services.msc)
You could open a command prompt, CD to the Debug or Release folder, and type the name of your exe. When I suggest this to people they think it is a lot of work, but here are the bare minimum clicks and keystrokes for this:
I think that's 14 keystrokes and clicks (counting shift-right-click as two for example) which really isn't much. Once you have the command prompt, of course, running it again is just up-arrow, enter.
I've installed and use VB6 for legacy projects many times on Windows 7.
What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.
Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721
Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm
I had the same problem today and have gone through the following path - (%USERPROFILE%\AppData\Roaming\npm) and came to know that there is some junk data and when I cleared everything under npm directory. Now when I ran (npm install command again). Now everything works fine.
I think the task scheduler would be overkill (imho). There is a startup folder for win7.
C:\Users\miliu\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Just create a shortcut for your autostart Applicaton, edit the properties of the shortcut and have it always run as administrator.
Your kids could close it of course, but if they are tech-savvy they always find a way to keep you out. I know i did when i was younger.
Good luck!
Just try to re-create connection. In my situation one of jdbc connection stopped working for no reason. From console sqlplus was working ok. It took me 2 hours to realize that If i create the same connection - it works.
I believe, things have changed now. On My Win 2008 R2 Box, I was able to register a 32 bit dll with a 64 bit regsvr32 as the 64 bit version can detect the target bitness and spawn a new 32 bit regsvr32 from %SYSWOW% folder.
MinGW uses a fairly old version of GCC (3.4.5, I believe), and hasn't been updated in a while. If you're already comfortable with the GCC toolset and just looking to get your feet wet in Windows programming, this may be a good option for you. There are lots of great IDEs available that use this compiler.
Edit: Apparently I was wrong; that's what I get for talking about something I know very little about. Tauran points out that there is a project that aims to provide the MinGW toolkit with the current version of GCC. You can download it from their website.
However, I'm not sure that I can recommend it for serious Windows development. If you're not a idealistic fanboy who can't stomach the notion of ever using Microsoft software, I highly recommend investigating Visual Studio, which comes bundled with Microsoft's C/C++ compiler. The Express version (which includes the same compiler as all the paid-for editions) is absolutely free for download. In addition to the compiler, Visual Studio also provides a world-class IDE that makes developing Windows-specific applications much easier. Yes, detractors will ramble on about the fact that it's not fully standards-compliant, but such is the world of writing Windows applications. They're never going to be truly portable once you include windows.h
, so most of the idealistic dedication just ends up being a waste of time.
If you use Git from cmd, try running it from Git Bash. In cmd, git.exe is actually a wrapper that sets up the correct environment every time you start it, and only then launches the real git.exe. It can take up to twice as much time as it's required to just do what you want. And Git Bash sets up the environment only when it starts.
For me, this was due to the user PATH environment variable, which didn't seem to work even though the user was correct, so I needed to put the entire executable path into the program field.
Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
(which references 32-bit programs) for part of the name of the program, or
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
(if it actually was a 64-bit program).
If you find something that matches your program in one of those, the contents of UninstallString
in that key usually give you the exact command you are looking for (that you can run in a script).
If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.
Then in a .bat script you can do
if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)
I don't think your question is very clear, this code assumes that if you're going to include the -domain parameter, it's always 'named' (i.e. dostuff computername arg2 -domain domain); this also makes the computername parameter mandatory.
Function DoStuff(){
param(
[Parameter(Mandatory=$true)][string]$computername,
[Parameter(Mandatory=$false)][string]$arg2,
[Parameter(Mandatory=$false)][string]$domain
)
if(!($domain)){
$domain = 'domain1'
}
write-host $domain
if($arg2){
write-host "arg2 present... executing script block"
}
else{
write-host "arg2 missing... exiting or whatever"
}
}
You can install multiple Java runtimes under Windows (including Windows 7) as long as each is in their own directory.
For example, if you are running Win 7 64-bit, or Win Server 2008 R2, you may install 32-bit JRE in "C:\Program Files (x86)\Java\jre6" and 64-bit JRE in "C:\Program Files\Java\jre6", and perhaps IBM Java 6 in "C:\Program Files (x86)\IBM\Java60\jre".
The Java Control Panel app theoretically has the ability to manage multiple runtimes: Java tab >> View... button
There are tabs for User and System settings. You can add additional runtimes with Add or Find, but once you have finished adding runtimes and hit OK, you have to hit Apply in the main Java tab frame, which is not as obvious as it could be - otherwise your changes will be lost.
If you have multiple versions installed, only the main version will auto-update. I have not found a solution to this apart from the weak workaround of manually updating whenever I see an auto-update, so I'd love to know if anyone has a fix for that.
Most Java IDEs allow you to select any Java runtime on your machine to build against, but if not using an IDE, you can easily manage this using environment variables in a cmd window. Your PATH and the JAVA_HOME variable determine which runtime is used by tools run from the shell. Set the JAVA_HOME to the jre directory you want and put the bin directory into your path (and remove references to other runtimes) - with IBM you may need to add multiple bin directories. This is pretty much all the set up that the default system Java does. You can also set CLASSPATH, ANT_HOME, MAVEN_HOME, etc. to unique values to match your runtime.
The hosted network won't start if there are other active wifi adapters.
Disable the others whilst you're starting the hosted network.
I created 2 servers, listening on same port 8081, running from same code, while learning
1st server creation shud have worked 2nd server creation failed with EADDRINUSE
node.js callback delays might be reason behind neither worked, or 2nd server creation had exception, and program exited, so 1st server is also closed
2 server issue hint, I got from: How to fix Error: listen EADDRINUSE while using nodejs?
It Seems the Port 80 is already in use. Try to Use some other Port which is not in use by any other application in your System.
It should be that the particular mvn
command exec
s and does not return, thereby not executing the rest of the commands.
The default generator for Windows seems to be set to NMAKE. Try to use:
cmake -G "MinGW Makefiles"
Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.
Simple pipe trick, ||
, with some .vbs used at top of your batch. It will exit regular and restart as administrator.
@AT>NUL||echo set shell=CreateObject("Shell.Application"):shell.ShellExecute "%~dpnx0",,"%CD%", "runas", 1:set shell=nothing>%~n0.vbs&start %~n0.vbs /realtime& timeout 1 /NOBREAK>nul& del /Q %~n0.vbs&cls&exit
It also del /Q
the temp.vbs when it's done using it.
When you log on Windows creates an access token. This identifies you, the groups you are a member of and your privileges. And note that whether a user is an administrator or not is determined by whether the user is a member of the Administrators group.
Without UAC, when you run a program it gets a copy of the access token, and this controls what the program can access.
With UAC, when you run a program it gets a restricted access token. This is the original access token with "Administrators" removed from the list of groups (and some other changes). Even though your user is a member of the Administrators group, the program can't use Administrator privileges.
When you select "Run as Administrator" and your user is an administrator the program is launched with the original unrestricted access token. If your user is not an administrator you are prompted for an administrator account, and the program is run under that account.
Go to the Eclipse base folder ? open eclipse.ini ? you will find the below line at line no 4:
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20150204-1316 plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120913-144807
As you can see, line 1 is of 64-bit Eclipse. It contains x86_64 and line 2 is of 32-bit Eclipse. It contains x_86.
For 32-bit Eclipse only x86 will be present and for 64-bit Eclipse x86_64 will be present.
Open the start menu and type cmd
into the search box
Hold Ctrl + Shift
and press Enter
This runs the Command Prompt in Administrator mode.
Now type regsvr32 MyComobject.dll
Though it may be unrelated to your question, take a look at GetGUIThreadInfo Function.
As per
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
you will want to add an application manifest if you don't already have one or don't know how to add one. As some projects don't automatically add a separate manifest file, first go to project properties, navigate to the Application tab and check to make sure your project is not excluding the manifest at the bottom of the tap.
from tkinter import *
from PIL import ImageTk, Image
Tk.call('wm', 'iconphoto', Tk._w, ImageTk.PhotoImage(Image.open('./resources/favicon.ico')))
The above worked for me.
Your code is absolutely fine. It just needs "exit 0" for a cleaner exit.
tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B
exit 0
If you are performing a new install of the SenseNet TaskManagement website on IIS (from source code, not WebPI), you will get this message, usually related to SignalR communication. As @nicole-caliniou points out, it is due to a key search in the Registry that fails.
To solve this for SenseNet TaskManagement v1.1.0, first find the registry key name in the web.config file. By default it is "SnTaskWeb".
<appSettings>
<add key="LogSourceName" value="SnTaskWeb" />
Open the registry editor, regedit.exe
, and navigate to HKLM\SYSTEM\CurrentControlSet\Services\EventLog\SnTask
. Right-click on SnTask and select New Key
, and name the key SnTaskWeb
for the configuration shown above. Then right-click on the SnTaskWeb
element and select New Expandable String Value
. The name should be EventMessageFile
and the value data should be C:\Windows\Microsoft.NET\Framework\v4.0.30319\EventLogMessages.dll
.
Keywords: signalr, sensenet, regedit, permissions
If you are willing to pay I strongly recommend you Telerik Components for WPF. They offer great styles/themes and there have specific themes for both, Office 2013 and Windows 8 (EDIT: and also a Visual Studio 2013 themed style). However there offering much more than just styles in fact you will get a whole bunch of controls which are really useful.
Here is how it looks in action (Screenshots taken from telerik samples):
Here are the links to the telerik executive dashboard sample (first screenshot) and here for the CRM Dashboard (second screenshot).
They offer a 30 day trial, just give it a shot!
This is the official solution for setting the Java environment from www.java.com - here.
There are solutions for Windows 7, Windows Vista, Windows XP, Linux/Solaris and other shells.
Windows 7
- Select Computer from the Start menu
- Choose System Properties from the context menu
- Click Advanced system settings -> Advanced tab
- Click on Environment Variables, under System Variables, find PATH, and click on it.
- In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
- Reopen Command prompt window, and run your Java code.
I am using excelcnv.exe to convert csv into xlsx and that seemed to work properly. You will have to change the directory to where your excelcnv is. If 32 bit, it goes to Program Files (x86)
Start-Process -FilePath 'C:\Program Files\Microsoft Office\root\Office16\excelcnv.exe' -ArgumentList "-nme -oice ""$xlsFilePath"" ""$xlsToxlsxPath"""
I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?
Basically, you use the /B
and /C
options:
START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1
I found this topic while searching for run script for startup and shutdown Windows 10. Those answers above didn't working. For me on windows 10 worked when I put scripts to task scheduler. How to do this: press window key and write Task scheduler, open it, then on the right is Add task... button. Here you can add scripts. PS: I found action for startup and logout user, there is not for shutdown.
Set the system to console, following the previous suggestions. Only, also had to change the character set to Unicode, see the snapshot of Visual Studio 2015 above.
The ensurepip
module was added in version 3.4 and then backported to 2.7.9.
So make sure your Python version is at least 2.7.9 if using Python 2, and at least 3.4 if using Python 3.
EDIT these lines in host file and it should work.
Host file usually located in C:\Windows\System32\drivers\etc\hosts
::1 localhost.localdomain localhost
127.0.0.1 localhost
Type "msg /?" in the command prompt to get various ways of sending meessages to a user.
Type "net send /?" in the command prompt to get another variation of sending messages across.
1) Download Ruby 1.9.3
2) cmd check command: ruby -v
'return result ruby 1.9.3 then success full install ruby
3) Download DevKit file from http://rubyinstaller.org/downloads (DevKit-tdm-32-4.5.2-20110712-1620-sfx.exe)
4) Extract DevKit to path C:\Ruby193\DevKit
5) cd C:\Ruby193\DevKit
6) ruby dk.rb init
7) ruby dk.rb review
8) ruby dk.rb install
9) cmd : gem install rails -v3.1.1
'few time installing full process'
10) cmd : rails -v
'return result rails 3.1.1 then its success fully install'
enjoy Ruby on Rails...
This issue is caused by the pipeline mode in your Application Pool setting that your web site is set to.
Short
Simple way (bad practice) Add the following to your web.config. See http://www.iis.net/ConfigReference/system.webServer/validation
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
Long If possible, your best bet is to change your application to support the integrated pipelines. There are a number of changes between IIS6 and IIS7.x that will cause this error. You can find details about these changes here http://learn.iis.net/page.aspx/381/aspnet-20-breaking-changes-on-iis-70/.
If you're unable to do that, you'll need to change the App pool which may be more difficult to do depending on your availability to the web server.
Check http://technet.microsoft.com/en-us/library/cc731755(WS.10).aspx for details on changing the App Pool
If you need to create an App Pool with Classic pipelines, take a look at http://technet.microsoft.com/en-us/library/cc731784(WS.10).aspx
If you don't have access to the server to make this change, you'll need to do this through your hosting server and contact them for help.
Feel free to ask questions.
@Cort3z: if the problem is still present, this hotfix: https://support.microsoft.com/en-us/kb/2891362 should solve it (from win7 sp1 to 8.1)
You can use PowerShell to generate a self-signed certificate with the new-selfsignedcertificate cmdlet:
New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My"
Note: makecert.exe is deprecated.
Cmdlet Reference: https://technet.microsoft.com/itpro/powershell/windows/pkiclient/new-selfsignedcertificate
You have to edit httpd.conf
and find this line: Listen 127.0.0.1:80
Then write down your desired IP you set for LAN. Don't use automatic IP.
e.g.: Listen 192.168.137.1:80
I used 192.167.137.1
as my LAN IP of Windows 7. Restart Apache and enjoy sharing.
nginx is useful for forwarding HTTP on many platforms including Windows. It's easy to setup and extend with more advanced configuration. A basic configuration could look something like this:
events {}
http {
server {
listen 192.168.1.111:4422;
location / {
proxy_pass http://192.168.2.33:80/;
}
}
}
To run the batch file when the VM
user logs in:
Drag the shortcut--the one that's currently on your desktop--(or the batch file itself) to Start - All Programs - Startup. Now when you login as that user, it will launch the batch file.
Another way to do the same thing is to save the shortcut or the batch file in %AppData%\Microsoft\Windows\Start Menu\Programs\Startup\
.
As far as getting it to run full screen, it depends a bit what you mean. You can have it launch maximized by editing your batch file like this:
start "" /max "C:\Program Files\Oracle\VirtualBox\VirtualBox.exe" --comment "VM" --startvm "12dada4d-9cfd-4aa7-8353-20b4e455b3fa"
But if VirtualBox has a truly full-screen mode (where it hides even the taskbar), you'll have to look for a command-line parameter on VirtualBox.exe. I'm not familiar with that product.
Another useful trick:
If you find a lot of files with same or similar name convention (like mac file with dot prefix name... that famous file pulltion), you can easily remove them with one single line from the powershell like this:
ls -r .* | rm
This line is going to remove all files with a dot in the begining of the name inside the current directory, and all files with same circumstances inside other folders inside this directory too. Be aware about it when using it. :D
I am using xampp 1.7.3. Using inspiration from here: xampp 1.7.3 upgrade broken virtual hosts access forbidden
INSTEAD OF add <Directory> .. </Directory>
in httpd-vhosts.conf, I add it in httpd.conf right after <Directory "D:/xampplite/cgi-bin"> .. </Directory>
.
Here is what I add in httpd.conf:
<Directory "D:/CofeeShop">
AllowOverride All
Options All
Order allow,deny
Allow from all
</Directory>
And here is what I add in httpd-vhosts.conf
<VirtualHost *:8001>
ServerAdmin [email protected]
DocumentRoot "D:/CofeeShop"
ServerName localhost:8001
</VirtualHost>
I also add Listen 8001
in httpd.conf to complete my setting.
Hope it helps
You can start your application as administrator if you add Application Manifest to your project.
Just Add New Item to your project and select "Application Manifest File". Change the <requestedExecutionLevel>
element to:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Just had the same issue on Windows Server 2008 R2 and nothing helped, not taskmanager or taskkill. But, windows powershell run as administrator worked with "kill -id pid"
16 bit installer will not work on windows 7 it's no longer supported by win 7 the most recent supported version of windows that can run 16 bit installer is vista 32-bit even vista 64-bit doesn't support 16-bit installer.... reference http://support.microsoft.com/kb/946765
You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'
The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.
As detailed in the Oracle Java SE Support Roadmap
After April 2015, Oracle will no longer post updates of Java SE 7 to its public download sites. Existing Java SE 7 downloads already posted as of April 2015 will remain accessible in the Java Archive
Check the Java SE 7 Archive Downloads page. The last release was update 80, therefore the 32-bit filename to download is jdk-7u80-windows-i586.exe
(64-bit is named jdk-7u80-windows-x64.exe
.
Old Java downloads also require a sign on to an Oracle account now :-( however with some crafty cookie creating one can use wget
to grab the file without signing in.
wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-windows-i586.exe"
Just turn off the firewall and remove the instance configuration. Add a new instance for the server.![Disable Firewall][1] Give he port number correctly as 3306 as default
Copy your SDK path and assign it to the environment variable ANDROID_SDK_ROOT
Refer pic below:
Had an issue where my task was not firing simply because it was running on a laptop without a power cord... Under the conditions tab, by default it is checked so that a task will not run while AC power is not connected.
I think it is better to change default port of Skype.
Open skype. Go to Tools, Options, Connections, change the port.
I found the answer: I need to add a new application to the service components in my computer and then add the right DLL's.
Thanks! If anyone has the same problem, I'll be happy to help.
You say it works once you install the VB6 IDE so the problem is likely to be that the components you are trying to use depend on the VB6 runtime being installed.
The VB6 runtime isn't installed on Windows by default.
Installing the IDE is one way to get the runtime. For non-developer machines, a "redistributable" installer package from Microsoft should be used instead.
Here is one VB6 runtime installer from Microsoft. I'm not sure if it will be the right version for your components:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=7b9ba261-7a9c-43e7-9117-f673077ffb3c
If there is any error at all in the PATH windows will silently disregard it. Things like having %PATH% or spaces between items in your path will break it. Be warned
in powershell enter the following:
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
close and open the powershell and try again. this should solve your problem.
New versions of application servers removed the ability of binding to your entire network interface and limited it just to the local interface (localhost). The reason being was for security. From what I know, Tomcat and JBoss implement the same security measures.
If you want to bind it to another IP you can explicitly set it in your connector string:
address="192.168.1.100"
-b 192.168.1.100
as a command line. Just remember that binding 0.0.0.0
allows anyone access to your box to access that server. It will bind to all addresses. If that is what you want, then use 0.0.0.0, if it isn't then specify the address you would like to explicitly bind instead.
Just make sure you understand the consequences binding to all addresses (0.0.0.0)
You have to enable the features in Add/Remove Programs section of your Control Panel. Select "Turn Windows features on or off"
Any file manager allow to avoid such issues, e.g Far Manager
By wrapping your comparisons in {}
in your first example you are creating ScriptBlocks; so the PowerShell interpreter views it as Where-Object { <ScriptBlock> -and <ScriptBlock> }
. Since the -and
operator operates on boolean values, PowerShell casts the ScriptBlocks to boolean values. In PowerShell anything that is not empty, zero or null is true. The statement then looks like Where-Object { $true -and $true }
which is always true.
Instead of using {}
, use parentheses ()
.
Also you want to use -eq
instead of -match
since match uses regex and will be true if the pattern is found anywhere in the string (try: 'xlsx' -match 'xls'
).
Invoke-Command -computername SERVERNAME {
Get-ChildItem -path E:\dfsroots\datastore2\public |
Where-Object {($_.extension -eq ".xls" -or $_.extension -eq ".xlk") -and ($_.creationtime -ge "06/01/2014")}
}
A better option is to filter the extensions at the Get-ChildItem
command.
Invoke-Command -computername SERVERNAME {
Get-ChildItem -path E:\dfsroots\datastore2\public\* -Include *.xls, *.xlk |
Where-Object {$_.creationtime -ge "06/01/2014"}
}
For me this did the trick at port 80 in the end:
You have to disable the http.sys service manually via the registry:
You should now find that Apache will start on port 80!
I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.
Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.
After this, Windows started prioritize Ethernet adapter.
Create a new addHostEntry.bat file with the following content in it:
@echo off
TITLE Modifying your HOSTS file
COLOR F0
ECHO.
:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"
IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%
ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop
:REJECTED
ECHO Your HOSTS file was left unchanged>>%systemroot%\Temp\hostFileUpdate.log
ECHO Finished.
GOTO END
:ACCEPTED
SET NEWLINE=^& echo.
ECHO Carrying out requested modifications to your HOSTS file
FIND /C /I "mydomain.com" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1 mydomain.com>>%WINDIR%\system32\drivers\etc\hosts
ECHO Finished
GOTO END
:END
ECHO.
ping -n 11 127.0.0.1 > nul
EXIT
Hope this helps!
I had the same problem. I am using mysql 5.6.11. To solve this problem I had to change my-default.ini file in mysql-5.6.11-win32 folder So I just pasted the following lines under line [mysqld]
basedir="D:\mysql-5.6.11-win32\"
datadir="D:\mysql-5.6.11-win32\data\"
port=3306
server-id=1
bind-address=127.0.0.1
Options basedir and datadir need to be modified for mysql location.
You can use this PowerShell command.
Clear-RecycleBin -Force
Note: If you want a confirmation prompt, remove the -Force flag
What you need to do is add
@ComponentScan("package/include/your/annotation/component")
in AppConfiguration.java
.
Since I think your AppConfiguraion.java
's package is deeper than your annotation component (@Service, @Component...)'s package,
such as "package/include/your/annotation/component/deeper/config"
.
This is what I do for those situations:
I don't start the html element with class 'hide', but I put style="display: none".
This is because bootstrap jquery modifies the style attribute and not the classes to hide/unhide.
Example:
<button type="button" id="btn_cancel" class="btn default" style="display: none">Cancel</button>
or
<button type="button" id="btn_cancel" class="btn default display-hide">Cancel</button>
Later on, you can run all the following that will work:
$('#btn_cancel').toggle() // toggle between hide/unhide
$('#btn_cancel').hide()
$('#btn_cancel').show()
You can also uso the class of Twitter Bootstrap 'display-hide', which also works with the jQuery IU .toggle() method.
This is all nicely lined up including the field label. Lining up the field label was the tricky part.
<div class="form-group">
<label class="control-label col-md-5">Create a</label>
<div class="col-md-7">
<label class="radio-inline control-label">
<input checked="checked" id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="2"> Task
</label>
<label class="radio-inline control-label">
<input id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="1"> Note
</label>
</div>
</div>
<div class="form-group">
@Html.Label("Create a", htmlAttributes: new { @class = "control-label col-md-5" })
<div class="col-md-7">
<label class="radio-inline control-label">
@Html.RadioButtonFor(model => model.TaskTypeId, Model.TaskTaskTypeId) Task
</label>
<label class="radio-inline control-label">
@Html.RadioButtonFor(model => model.TaskTypeId, Model.NoteTaskTypeId) Note
</label>
</div>
</div>
int main()
{
long mylong = 123456789;
string mystring;
stringstream mystream;
mystream << mylong;
mystring = mystream.str();
cout << mystring << "\n";
return 0;
}
q = input("Apple")
w = input("Ball")
Definition = {'apple': q, 'ball': w}
a = [5, 1, 6, 14, 2, 8]
b = [2, 6, 15]
a - b
# => [5, 1, 14, 8]
b - a
# => [15]
(b - a).empty?
# => false
If you are working on a windows forms project you can try the following:
Add items to the ListBox
as KeyValuePair
objects:
listBox.Items.Add(new KeyValuePair(key, value);
Then you will be able to retrieve them the following way:
KeyValuePair keyValuePair = listBox.Items[index];
var value = keyValuePair.Value;
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
ColumnName = column.ColumnName;
ColumnData = row[column].ToString();
}
}
I tried the above answers as of vscode 1.42.1 and they worked inasmuch as to get me a git bash terminal. So, bottom line this setting works just for opening a bash shell from terminal:
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
However it has the unwanted side effect of also being the shell used to build things and that breaks the MS C++ chain because the \
character used for path separator is understood by bash as an escape character. The complete fix for me then required me to add this extra variable, setting it to powershell:
"terminal.integrated.automationShell.windows": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
Now, I can have my bash terminal and Ctrl-Shift-B
or F5
work without problems.
Oh, and as other posters mentioned, the source for this information is VSCode's documentation.
@NathanClement was a bit faster. Yet, here is the complete code (slightly more elaborate):
Option Explicit
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Set shtToExport = ThisWorkbook.Worksheets("Sheet1") 'Sheet to export as CSV
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False 'Possibly overwrite without asking
wbkExport.SaveAs Filename:="C:\tmp\test.csv", FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
End Sub
The table normally contains multiple rows. Use a loop and use row.Field<string>(0)
to access the value of each row.
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>("File");
}
You can also access it via index:
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>(0);
}
If you expect only one row, you can also use the indexer of DataRowCollection
:
string file = dt.Rows[0].Field<string>(0);
Since this fails if the table is empty, use dt.Rows.Count
to check if there is a row:
if(dt.Rows.Count > 0)
file = dt.Rows[0].Field<string>(0);
from numpy import prod
def factorial(n):
print prod(range(1,n+1))
or with mul from operator:
from operator import mul
def factorial(n):
print reduce(mul,range(1,n+1))
or completely without help:
def factorial(n):
print reduce((lambda x,y: x*y),range(1,n+1))
Simple printf() function from O'Reilly's Python Cookbook.
import sys
def printf(format, *args):
sys.stdout.write(format % args)
Example output:
i = 7
pi = 3.14159265359
printf("hi there, i=%d, pi=%.2f\n", i, pi)
# hi there, i=7, pi=3.14
First, you are asking the impossible. An old-fashioned Date
object hasn’t got, as in cannot have a time zone or GMT offset.
But the date is always is interpreted in my local time zone.
I suppose that you have printed the Date
or done something else that implicitly calls it toString
method. I believe that this is the only time that the Date
is interpreted in your time zone. More precisely in the current default time zone of your JVM. On the other hand this is unavoidable. Date.toString()
does behave in that way, it picks up the JVM’s time zone setting and uses it for rendering the string to be returned.
You shouldn’t use a Date
, though. That class is poorly designed and fortunately long outdated. Also java.time, the modern Java date and time API that replaces it, has a class or two for dates and times with offset from GMT or UTC. I am considering GMT and UTC synonymous for now, strictly speaking they are not.
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
System.out.println("Time now in UTC (GMT) is " + now);
When I ran this snippet just now, the output was:
Time now in UTC (GMT) is 2019-06-17T11:51:38.246188Z
The trailing Z
of the output means UTC.
Since getJdbcTemplate().queryForMap expects minimum size of one but when it returns null it shows EmptyResultDataAccesso fix dis when can use below logic
Map<String, String> loginMap =null;
try{
loginMap = getJdbcTemplate().queryForMap(sql, new Object[] {CustomerLogInInfo.getCustLogInEmail()});
}
catch(EmptyResultDataAccessException ex){
System.out.println("Exception.......");
loginMap =null;
}
if(loginMap==null || loginMap.isEmpty()){
return null;
}
else{
return loginMap;
}
When installing SQL Express, you'll usually get a named instance called SQLExpress, which as others have said you can connect to with localhost\SQLExpress.
If you're looking to get a 'default' instance, which doesn't have a name, you can do that as well. If you put MSSQLServer as the name when installing, it will create a default instance which you can connect to by just specifying 'localhost'.
For Android, and using Apache's Commons IO Library for IOUtils
:
// connection is a HttpURLConnection
InputStream inputStream = connection.getInputStream()
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(inputStream, baos);
JSONObject jsonObject = new JSONObject(baos.toString()); // JSONObject is part of Android library
Another version with Promise's modern method. It's shorter that the others responses based on Promise :
const readFiles = (dirname) => {
const readDirPr = new Promise( (resolve, reject) => {
fs.readdir(dirname,
(err, filenames) => (err) ? reject(err) : resolve(filenames))
});
return readDirPr.then( filenames => Promise.all(filenames.map((filename) => {
return new Promise ( (resolve, reject) => {
fs.readFile(dirname + filename, 'utf-8',
(err, content) => (err) ? reject(err) : resolve(content));
})
})).catch( error => Promise.reject(error)))
};
readFiles(sourceFolder)
.then( allContents => {
// handle success treatment
}, error => console.log(error));
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.
You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/
Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API
A similar looking answer was downvoted. But I think I can justify what I'm suggesting here for limited cases.
While it's true that an observable doesn't have a current value, very often it will have an immediately available value. For example with redux / flux / akita stores you may request data from a central store, based on a number of observables and that value will generally be immediately available.
If this is the case then when you subscribe
, the value will come back immediately.
So let's say you had a call to a service, and on completion you want to get the latest value of something from your store, that potentially might not emit:
You might try to do this (and you should as much as possible keep things 'inside pipes'):
serviceCallResponse$.pipe(withLatestFrom(store$.select(x => x.customer)))
.subscribe(([ serviceCallResponse, customer] => {
// we have serviceCallResponse and customer
});
The problem with this is that it will block until the secondary observable emits a value, which potentially could be never.
I found myself recently needing to evaluate an observable only if a value was immediately available, and more importantly I needed to be able to detect if it wasn't. I ended up doing this:
serviceCallResponse$.pipe()
.subscribe(serviceCallResponse => {
// immediately try to subscribe to get the 'available' value
// note: immediately unsubscribe afterward to 'cancel' if needed
let customer = undefined;
// whatever the secondary observable is
const secondary$ = store$.select(x => x.customer);
// subscribe to it, and assign to closure scope
sub = secondary$.pipe(take(1)).subscribe(_customer => customer = _customer);
sub.unsubscribe();
// if there's a delay or customer isn't available the value won't have been set before we get here
if (customer === undefined)
{
// handle, or ignore as needed
return throwError('Customer was not immediately available');
}
});
Note that for all of the above I'm using subscribe
to get the value (as @Ben discusses). Not using a .value
property, even if I had a BehaviorSubject
.
for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d
pushd %curdir%
One thing to be mindful of is setting strings then referring back to them. You have to make sure the quotes aren't colliding.
set start_date = '2019-01-21';
select ${hiveconf:start_date};
When setting dates then referring to them in code as the strings can conflict. This wouldn't work with the start_date set above.
'${hiveconf:start_date}'
We have to be mindful of not setting twice single or double quotes for strings when referring back to them in the query.
I had the same problem.
I had to print the color of the nodes where the color was: enum col { WHITE, GRAY, BLACK };
and the node: typedef struct Node { col color; };
I tried to print node->color
with printf("%s\n", node->color);
but all I got on the screen was (null)\n
.
The answer bmargulies gave almost solved the problem.
So my final solution is:
static char *enumStrings[] = {"WHITE", "GRAY", "BLACK"};
printf("%s\n", enumStrings[node->color]);
const Root = ({ session }) => {
const isLoggedIn = session && session.getCurrentUser
return (
<Router>
{!isLoggedIn ? (
<Switch>
<Route path="/signin" component={<Signin />} />
<Redirect to="/signin" />
</Switch>
) : (
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/something-else" component={SomethingElse} />
<Redirect to="/" />
</Switch>
)}
</Router>
)
}
I'm using python 2.7.13 with scandir and here's my one-liner recursive function to get the total size of a folder:
from scandir import scandir
def getTotFldrSize(path):
return sum([s.stat(follow_symlinks=False).st_size for s in scandir(path) if s.is_file(follow_symlinks=False)]) + \
+ sum([getTotFldrSize(s.path) for s in scandir(path) if s.is_dir(follow_symlinks=False)])
>>> print getTotFldrSize('.')
1203245680
One thing you could do would be to create a dictionary. Might be a little sloppy considering your looking for 64 elements but it gets the job done. Im not sure if its the "preferred way" to do it but it worked for me using an array of structs.
var tasks = [0:[forTasks](),1:[forTasks](),2:[forTasks](),3:[forTasks](),4:[forTasks](),5:[forTasks](),6:[forTasks]()]
Another alternative to the accepted answer that avoids any issues with matrix multiplication:
def MSE(Y, YH):
return np.square(Y - YH).mean()
From the documents for np.square: "Return the element-wise square of the input."
I don't like using wait
because it gets blocked until the process exits, which is not ideal when there are multiple process to wait on as I can't get a status update until the current process is done. I prefer to use a combination of kill -0
and sleep
to this.
Given an array of pids
to wait on, I use the below waitPids()
function to get a continuous feedback on what pids are still pending to finish.
declare -a pids
waitPids() {
while [ ${#pids[@]} -ne 0 ]; do
echo "Waiting for pids: ${pids[@]}"
local range=$(eval echo {0..$((${#pids[@]}-1))})
local i
for i in $range; do
if ! kill -0 ${pids[$i]} 2> /dev/null; then
echo "Done -- ${pids[$i]}"
unset pids[$i]
fi
done
pids=("${pids[@]}") # Expunge nulls created by unset.
sleep 1
done
echo "Done!"
}
When I start a process in the background, I add its pid immediately to the pids
array by using this below utility function:
addPid() {
local desc=$1
local pid=$2
echo "$desc -- $pid"
pids=(${pids[@]} $pid)
}
Here is a sample that shows how to use:
for i in {2..5}; do
sleep $i &
addPid "Sleep for $i" $!
done
waitPids
And here is how the feedback looks:
Sleep for 2 -- 36271
Sleep for 3 -- 36272
Sleep for 4 -- 36273
Sleep for 5 -- 36274
Waiting for pids: 36271 36272 36273 36274
Waiting for pids: 36271 36272 36273 36274
Waiting for pids: 36271 36272 36273 36274
Done -- 36271
Waiting for pids: 36272 36273 36274
Done -- 36272
Waiting for pids: 36273 36274
Done -- 36273
Waiting for pids: 36274
Done -- 36274
Done!
You can make function getStyles
that'll take an element and other arguments are properties that's values you want.
const convertRestArgsIntoStylesArr = ([...args]) => {
return args.slice(1);
}
const getStyles = function () {
const args = [...arguments];
const [element] = args;
let stylesProps = [...args][1] instanceof Array ? args[1] : convertRestArgsIntoStylesArr(args);
const styles = window.getComputedStyle(element);
const stylesObj = stylesProps.reduce((acc, v) => {
acc[v] = styles.getPropertyValue(v);
return acc;
}, {});
return stylesObj;
};
Now, you can use this function like this:
const styles = getStyles(document.body, "height", "width");
OR
const styles = getStyles(document.body, ["height", "width"]);
You're overcomplicating things:
var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
e.attr('id', 'myid');
$('#box').append(e);
For example: http://jsfiddle.net/ambiguous/Dm5J2/
To determine the package version in node code, you can use the following:
const version = require('./package.json').version;
for < ES6 versions
import {version} from './package.json';
for ES6 version
const version = process.env.npm_package_version;
if application has been started using npm start
, all npm_* environment variables become available.
You can use following npm packages as well - root-require, pkginfo, project-version.
Easiest way is used the Date Using Date() and getTime()
Date dte=new Date();
long milliSeconds = dte.getTime();
String strLong = Long.toString(milliSeconds);
System.out.println(milliSeconds)
The API doc for IllegalArgumentException
:
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
From looking at how it is used in the JDK libraries, I would say:
It seems like a defensive measure to complain about obviously bad input before the input can get into the works and cause something to fail halfway through with a nonsensical error message.
It's used for cases where it would be too annoying to throw a checked exception (although it makes an appearance in the java.lang.reflect code, where concern about ridiculous levels of checked-exception-throwing is not otherwise apparent).
I would use IllegalArgumentException
to do last ditch defensive argument checking for common utilities (trying to stay consistent with the JDK usage). Or where the expectation is that a bad argument is a programmer error, similar to an NullPointerException
. I wouldn't use it to implement validation in business code. I certainly wouldn't use it for the email example.
I had the same problem, even after increasing the size of the problematic columns in the table.
tl;dr: The length of the matching columns in corresponding Table Types may also need to be increased.
In my case, the error was coming from the Data Export service in Microsoft Dynamics CRM, which allows CRM data to be synced to an SQL Server DB or Azure SQL DB.
After a lengthy investigation, I concluded that the Data Export service must be using Table-Valued Parameters:
You can use table-valued parameters to send multiple rows of data to a Transact-SQL statement or a routine, such as a stored procedure or function, without creating a temporary table or many parameters.
As you can see in the documentation above, Table Types are used to create the data ingestion procedure:
CREATE TYPE LocationTableType AS TABLE (...);
CREATE PROCEDURE dbo.usp_InsertProductionLocation
@TVP LocationTableType READONLY
Unfortunately, there is no way to alter a Table Type, so it has to be dropped & recreated entirely. Since my table has over 300 fields (), I created a query to facilitate the creation of the corresponding Table Type based on the table's columns definition (just replace [table_name]
with your table's name):
SELECT 'CREATE TYPE [table_name]Type AS TABLE (' + STRING_AGG(CAST(field AS VARCHAR(max)), ',' + CHAR(10)) + ');' AS create_type
FROM (
SELECT TOP 5000 COLUMN_NAME + ' ' + DATA_TYPE
+ IIF(CHARACTER_MAXIMUM_LENGTH IS NULL, '', CONCAT('(', IIF(CHARACTER_MAXIMUM_LENGTH = -1, 'max', CONCAT(CHARACTER_MAXIMUM_LENGTH,'')), ')'))
+ IIF(DATA_TYPE = 'decimal', CONCAT('(', NUMERIC_PRECISION, ',', NUMERIC_SCALE, ')'), '')
AS field
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '[table_name]'
ORDER BY ORDINAL_POSITION) AS T;
After updating the Table Type, the Data Export service started functioning properly once again! :)
Here are the steps I followed to recover from a corrupt blob object.
1) Identify corrupt blob
git fsck --full
error: inflate: data stream error (incorrect data check)
error: sha1 mismatch 241091723c324aed77b2d35f97a05e856b319efd
error: 241091723c324aed77b2d35f97a05e856b319efd: object corrupt or missing
...
Corrupt blob is 241091723c324aed77b2d35f97a05e856b319efd
2) Move corrupt blob to a safe place (just in case)
mv .git/objects/24/1091723c324aed77b2d35f97a05e856b319efd ../24/
3) Get parent of corrupt blob
git fsck --full
Checking object directories: 100% (256/256), done.
Checking objects: 100% (70321/70321), done.
broken link from tree 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180
to blob 241091723c324aed77b2d35f97a05e856b319efd
Parent hash is 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180.
4) Get file name corresponding to corrupt blob
git ls-tree 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180
...
100644 blob 241091723c324aed77b2d35f97a05e856b319efd dump.tar.gz
...
Find this particular file in a backup or in the upstream git repository (in my case it is dump.tar.gz). Then copy it somewhere inside your local repository.
5) Add previously corrupted file in the git object database
git hash-object -w dump.tar.gz
6) Celebrate!
git gc
Counting objects: 75197, done.
Compressing objects: 100% (21805/21805), done.
Writing objects: 100% (75197/75197), done.
Total 75197 (delta 52999), reused 69857 (delta 49296)
Try this:
<img v-bind:src="'/media/avatars/' + joke.avatar" />
Don't forget single quote around your path string. also in your data check you have correctly defined image variable.
joke: {
avatar: 'image.jpg'
}
A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output
In case you are willing to use Curl for the calls with JSON 2 and Spring 3.2.0 in hand checkout the FAQ here. As AnnotationMethodHandlerAdapter is deprecated and replaced by RequestMappingHandlerAdapter.
This answer changes with .NET 4.5. Creating a zip file becomes incredibly easy. No third-party libraries will be required.
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
I had the same issue working on a project with Maven. Here how I fixed it: I just put the sources (images, musics and other stuffs) in the resources directory:
src/main/resources
I created the same structure for the packages in the resources directory too. For example:
If my class is on
com.package1.main
In the resources directory I put one package with the same name
com.package1.main
So I use
getClass().getResource("resource.png");
You have to self join stuff and match name and city. Then group by count.
select
s.id, s.name, s.city
from stuff s join stuff p ON (
s.name = p.city OR s.city = p.name
)
group by s.name having count(s.name) > 1
You can use a Contains
query for this:
var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));
If you do not want to compile it yourself you can go to:
Applications?Ubuntu Software Center?Edit?Software Sources?Updates
there you can check hardy-proposed is ticked(for 14.10 will be utopic-proposed)
Source
then simply go to terminal and type:
sudo apt-get install mysql-workbench
As a note, you will get other updates to, witch may not be stable!!!
var words_in_text = function (text) {
var regex = /([\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]+)/g;
return text.match(regex);
};
words_in_text('Düsseldorf, Köln, ??????, ???, ??????? !@#$');
// returns array ["Düsseldorf", "Köln", "??????", "???", "???????"]
This regex will match all words in the text of any language...
This answer is an extension to @raphadko's answer.
If you need to extract manually the captcha code (like in ajax requests) you have to call:
grecaptcha.getResponse(widget_id)
But how can you retrieve the widget id parameter?
I use this definition of CaptchaCallback to store the widget id of each g-recaptcha box (as an HTML data attribute):
var CaptchaCallback = function() {
jQuery('.g-recaptcha').each(function(index, el) {
var widgetId = grecaptcha.render(el, {'sitekey' : 'your code'});
jQuery(this).attr('data-widget-id', widgetId);
});
};
Then I can call:
grecaptcha.getResponse(jQuery('#your_recaptcha_box_id').attr('data-widget-id'));
to extract the code.
I ran into this challenge today in OSX El Capitan with Chrome v51. The page in question worked fine in Safari. I tried nearly every suggestion on this page - none worked right - all had side-effects... I ended up implementing the code below - super simple - no side-effects (still works as before in Safari).
Solution: Toggle a class on the problematic element as needed. Each toggle will force a redraw. (I used jQuery for convenience, but vanilla JavaScript should be no problem...)
jQuery Class Toggle
$('.slide.force').toggleClass('force-redraw');
CSS Class
.force-redraw::before { content: "" }
And that's it...
NOTE: You have to run the snippet below "Full Page" in order to see the effect.
$(window).resize(function() {_x000D_
$('.slide.force').toggleClass('force-redraw');_x000D_
});
_x000D_
.force-redraw::before {_x000D_
content: "";_x000D_
}_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
overflow: hidden;_x000D_
}_x000D_
.slide-container {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
overflow-x: scroll;_x000D_
overflow-y: hidden;_x000D_
white-space: nowrap;_x000D_
padding-left: 10%;_x000D_
padding-right: 5%;_x000D_
}_x000D_
.slide {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
height: 30%;_x000D_
border: 1px solid green;_x000D_
}_x000D_
.slide-sizer {_x000D_
height: 160%;_x000D_
pointer-events: none;_x000D_
//border: 1px solid red;_x000D_
_x000D_
}_x000D_
.slide-contents {_x000D_
position: absolute;_x000D_
top: 10%;_x000D_
left: 10%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>_x000D_
This sample code is a simple style-based solution to maintain aspect ratio of an element based on a dynamic height. As you increase and decrease the window height, the elements should follow and the width should follow in turn to maintain the aspect ratio. You will notice that in Chrome on OSX (at least), the "Not Forced" element does not maintain a proper ratio._x000D_
</p>_x000D_
<div class="slide-container">_x000D_
<div class="slide">_x000D_
<img class="slide-sizer" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">_x000D_
<div class="slide-contents">_x000D_
Not Forced_x000D_
</div>_x000D_
</div>_x000D_
<div class="slide force">_x000D_
<img class="slide-sizer" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">_x000D_
<div class="slide-contents">_x000D_
Forced_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
This should work
function updatePostID(val)
{
document.getElementById('PostID').value = val;
//and probably call document.forms[0].submit();
}
Then have a hidden field or other control for the PostID
@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)
Also you can do like this:
<select class="form-control postType" ng-model="selectedProd">
<option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>
where "selectedProd" will be selected product.
I know it's late, but I take the original code and change some stuff to control easily the css. So I made a code with the addClass() and the removeClass()
Here the full code : http://jsfiddle.net/e5qaD/4837/
if( bottom_of_window > bottom_of_object ){
$(this).addClass('showme');
}
if( bottom_of_window < bottom_of_object ){
$(this).removeClass('showme');
You can use update_columns
:
User.first.update_columns({:name => "sebastian", :age => 25})
Updates the given attributes of an object, without calling save, hence skipping validations and callbacks.
Take a look at the java.sql.PreparedStatement class, specifically the function
Then take a look at the java.sql.ResultSet class, specifically the function
http://java.sun.com/javase/6/docs/api/java/sql/ResultSet.html#getBinaryStream(int)
Keep in mind that if you are serializing an object into a database, and then you change the object in your code in a new version, the deserialization process can easily fail because your object's signature changed. I once made this mistake with storing a custom Preferences serialized and then making a change to the Preferences definition. Suddenly I couldn't read any of the previously serialized information.
You might be better off writing clunky per property columns in a table and composing and decomposing the object in this manner instead, to avoid this issue with object versions and deserialization. Or writing the properties into a hashmap of some sort, like a java.util.Properties object, and then serializing the properties object which is extremely unlikely to change.
length
and dbms_lob.getlength
return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength
will return the number of bytes, which may differ from the number of characters in a multi-byte character set.
As the documentation doesn't specify what happens when you apply length
on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength
.
I would do it by creating a variable that points to the nodes that have the proper value in Value1 then referring to t
<xsl:variable name="myVarANode" select="root//DataSet/Data[@Value1='2']" />
<xsl:value-of select="$myVarANode/@Value2"/>
Everyone else's answers are right too - more right in fact since I didn't notice the extra slash in your XPATH that would mess things up. Still, this will also work , and might work for different things, so keep this method in your toolbox.
I had similar issue with the index.html being cached by the browser or more tricky by middle cdn/proxies (F5 will not help you).
I looked for a solution which verifies 100% that the client has the latest index.html version, luckily I found this solution by Henrik Peinar:
https://blog.nodeswat.com/automagic-reload-for-clients-after-deploy-with-angular-4-8440c9fdd96c
The solution solve also the case where the client stays with the browser open for days, the client checks for updates on intervals and reload if newer version deployd.
The solution is a bit tricky but works like a charm:
ng cli -- prod
produces hashed files with one of them called main.[hash].jsSince Henrik Peinar solution was for angular 4, there were minor changes, I place also the fixed scripts here:
VersionCheckService :
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class VersionCheckService {
// this will be replaced by actual hash post-build.js
private currentHash = '{{POST_BUILD_ENTERS_HASH_HERE}}';
constructor(private http: HttpClient) {}
/**
* Checks in every set frequency the version of frontend application
* @param url
* @param {number} frequency - in milliseconds, defaults to 30 minutes
*/
public initVersionCheck(url, frequency = 1000 * 60 * 30) {
//check for first time
this.checkVersion(url);
setInterval(() => {
this.checkVersion(url);
}, frequency);
}
/**
* Will do the call and check if the hash has changed or not
* @param url
*/
private checkVersion(url) {
// timestamp these requests to invalidate caches
this.http.get(url + '?t=' + new Date().getTime())
.subscribe(
(response: any) => {
const hash = response.hash;
const hashChanged = this.hasHashChanged(this.currentHash, hash);
// If new version, do something
if (hashChanged) {
// ENTER YOUR CODE TO DO SOMETHING UPON VERSION CHANGE
// for an example: location.reload();
// or to ensure cdn miss: window.location.replace(window.location.href + '?rand=' + Math.random());
}
// store the new hash so we wouldn't trigger versionChange again
// only necessary in case you did not force refresh
this.currentHash = hash;
},
(err) => {
console.error(err, 'Could not get version');
}
);
}
/**
* Checks if hash has changed.
* This file has the JS hash, if it is a different one than in the version.json
* we are dealing with version change
* @param currentHash
* @param newHash
* @returns {boolean}
*/
private hasHashChanged(currentHash, newHash) {
if (!currentHash || currentHash === '{{POST_BUILD_ENTERS_HASH_HERE}}') {
return false;
}
return currentHash !== newHash;
}
}
change to main AppComponent:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private versionCheckService: VersionCheckService) {
}
ngOnInit() {
console.log('AppComponent.ngOnInit() environment.versionCheckUrl=' + environment.versionCheckUrl);
if (environment.versionCheckUrl) {
this.versionCheckService.initVersionCheck(environment.versionCheckUrl);
}
}
}
The post-build script that makes the magic, post-build.js:
const path = require('path');
const fs = require('fs');
const util = require('util');
// get application version from package.json
const appVersion = require('../package.json').version;
// promisify core API's
const readDir = util.promisify(fs.readdir);
const writeFile = util.promisify(fs.writeFile);
const readFile = util.promisify(fs.readFile);
console.log('\nRunning post-build tasks');
// our version.json will be in the dist folder
const versionFilePath = path.join(__dirname + '/../dist/version.json');
let mainHash = '';
let mainBundleFile = '';
// RegExp to find main.bundle.js, even if it doesn't include a hash in it's name (dev build)
let mainBundleRegexp = /^main.?([a-z0-9]*)?.js$/;
// read the dist folder files and find the one we're looking for
readDir(path.join(__dirname, '../dist/'))
.then(files => {
mainBundleFile = files.find(f => mainBundleRegexp.test(f));
if (mainBundleFile) {
let matchHash = mainBundleFile.match(mainBundleRegexp);
// if it has a hash in it's name, mark it down
if (matchHash.length > 1 && !!matchHash[1]) {
mainHash = matchHash[1];
}
}
console.log(`Writing version and hash to ${versionFilePath}`);
// write current version and hash into the version.json file
const src = `{"version": "${appVersion}", "hash": "${mainHash}"}`;
return writeFile(versionFilePath, src);
}).then(() => {
// main bundle file not found, dev build?
if (!mainBundleFile) {
return;
}
console.log(`Replacing hash in the ${mainBundleFile}`);
// replace hash placeholder in our main.js file so the code knows it's current hash
const mainFilepath = path.join(__dirname, '../dist/', mainBundleFile);
return readFile(mainFilepath, 'utf8')
.then(mainFileData => {
const replacedFile = mainFileData.replace('{{POST_BUILD_ENTERS_HASH_HERE}}', mainHash);
return writeFile(mainFilepath, replacedFile);
});
}).catch(err => {
console.log('Error with post build:', err);
});
simply place the script in (new) build folder run the script using node ./build/post-build.js
after building dist folder using ng build --prod
There is the easy way
HTML:
<input type="checkbox" name="test[]" />x
<input type="checkbox" name="test[]" />y
<input type="checkbox" name="test[]" />z
<button type="button" id="submit">Submit</button>
JQUERY:
$("#submit").on("click",function(){
if (($("input[name*='test']:checked").length)<=0) {
alert("You must check at least 1 box");
}
return true;
});
For this you not need any plugin. Enjoy;)
Just use That.Its Easy.
<script language="javascript" type="text/javascript">
var images = new Array()
images[0] = "img1.jpg";
images[1] = "img2.jpg";
images[2] = "img3.jpg";
setInterval("changeImage()", 30000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
if (images.length == x)
{
x = 0;
}
}
</script>
And in Body Write this Code:-
<img id="img" src="imgstart.jpg">
For my case removing input type did the trick, i was using android:inputType="textPostalAddress" due to that my textview was sticked to one line and was not wrapping, removing this fixed the issue.
I went around the issue by including a checkbox depending on what form the person wanted to do. Then used 1 button to submit the whole form.
The Go Programming Language Specification
Appending to and copying slices
The function copy copies slice elements from a source src to a destination dst and returns the number of elements copied. Both arguments must have identical element type T and must be assignable to a slice of type []T. The number of elements copied is the minimum of len(src) and len(dst). As a special case, copy also accepts a destination argument assignable to type []byte with a source argument of a string type. This form copies the bytes from the string into the byte slice.
copy(dst, src []T) int copy(dst []byte, src string) int
tmp
needs enough room for arr
. For example,
package main
import "fmt"
func main() {
arr := []int{1, 2, 3}
tmp := make([]int, len(arr))
copy(tmp, arr)
fmt.Println(tmp)
fmt.Println(arr)
}
Output:
[1 2 3]
[1 2 3]
This is in answer to your question...
I'd also like to know how to make it open up in Sublime Text 2 instead
For Windows:
git config --global core.editor "'C:/Program Files/Sublime Text 2/sublime_text.exe'"
Check that the path for sublime_text.exe
is correct and adjust if needed.
For Mac/Linux:
git config --global core.editor "subl -n -w"
If you get an error message such as:
error: There was a problem with the editor 'subl -n -w'.
Create the alias for subl
sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl
Again check that the path matches for your machine.
For Sublime Text simply save cmd S
and close the window cmd W
to return to git.
Use MySQL FIND_IN_SET function:
SELECT *
FROM table_name
WHERE id IN (..,..,..,..)
ORDER BY FIND_IN_SET (coloumn_name, .., .., ..);
You don't really need jQuery for this as there is a Media API that provides you with all you need.
var video = document.getElementById('myVideo');
video.src = 'my_video_' + value + '.ogg';
video.load();
The Media API also contains a load()
method which: "Causes the element to reset and start selecting and loading a new media resource from scratch."
(Ogg isn't the best format to use, as it's only supported by a limited number of browsers. I'd suggest using WebM and MP4 to cover all major browsers - you can use the canPlayType()
function to decide on which one to play).
You can then wait for either the loadedmetadata
or loadeddata
(depending on what you want) events to fire:
video.addEventListener('loadeddata', function() {
// Video is loaded and can be played
}, false);
Here is a short, flexible snippet to convert a datetime-string in a cross-browser-safe fashion as nicel detailed by @drankin2112.
var inputTimestamp = "2014-04-29 13:00:15"; //example
var partsTimestamp = inputTimestamp.split(/[ \/:-]/g);
if(partsTimestamp.length < 6) {
partsTimestamp = partsTimestamp.concat(['00', '00', '00'].slice(0, 6 - partsTimestamp.length));
}
//if your string-format is something like '7/02/2014'...
//use: var tstring = partsTimestamp.slice(0, 3).reverse().join('-');
var tstring = partsTimestamp.slice(0, 3).join('-');
tstring += 'T' + partsTimestamp.slice(3).join(':') + 'Z'; //configure as needed
var timestamp = Date.parse(tstring);
Your browser should provide the same timestamp result as Date.parse
with:
(new Date(tstring)).getTime()
Forever takes command line options for output:
-l LOGFILE Logs the forever output to LOGFILE
-o OUTFILE Logs stdout from child script to OUTFILE
-e ERRFILE Logs stderr from child script to ERRFILE
For example:
forever start -o out.log -e err.log my-script.js
See here for more info
I would use EHP
Here it is:
from ehp import *
doc = '''<html>
<head>Heading</head>
<body attr1='val1'>
<div class='container'>
<div id='class'>Something here</div>
<div>Something else</div>
</div>
</body>
</html>
'''
html = Html()
dom = html.feed(doc)
for ind in dom.find('div', ('class', 'container')):
print ind.text()
Output:
Something here
Something else
Use DefinePlugin.
The DefinePlugin allows you to create global constants which can be configured at compile time.
new webpack.DefinePlugin(definitions)
plugins: [
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true)
})
//...
]
console.log(`Environment is in production: ${PRODUCTION}`);
You can do this easily with a matplotlib AxisDivider.
The example from the linked page also works without using subplots:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)))
# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)
Your program has no knowledge of where your VS project is, so see get path for my .exe and go ../..
to get your project's path.
Your count never equals the value 100 so your loop will continue until that is true
Replace your while clause with
def gukan(count):
while count < 100:
print(count)
count=count+3;
gukan(0)
and this will fix your problem, the program is executing correctly given the conditions you have given it.
Not sure, if I understand your question correctly.
If you have data in MS-Access, which you want to move it to SQL Server - you could use DTS.
And, I guess you could use SQL profiler to see all the INSERT statements going by, I suppose.
The correct format for IE8 is:
$("#ActionBox").css({ 'margin-top': '10px' });
with this work.
one url to the same view! like so!
urls.py
url(r'^$', views.landing.as_view(), name = 'landing'),
views.py
class landing(View):
template_name = '/home.html'
form_class1 = forms.pynamehere1
form_class2 = forms.pynamehere2
def get(self, request):
form1 = self.form_class1(None)
form2 = self.form_class2(None)
return render(request, self.template_name, { 'register':form1, 'login':form2,})
def post(self, request):
if request.method=='POST' and 'htmlsubmitbutton1' in request.POST:
## do what ever you want to do for first function ####
if request.method=='POST' and 'htmlsubmitbutton2' in request.POST:
## do what ever you want to do for second function ####
## return def post###
return render(request, self.template_name, {'form':form,})
/home.html
<!-- #### form 1 #### -->
<form action="" method="POST" >
{% csrf_token %}
{{ register.as_p }}
<button type="submit" name="htmlsubmitbutton1">Login</button>
</form>
<!--#### form 2 #### -->
<form action="" method="POST" >
{% csrf_token %}
{{ login.as_p }}
<button type="submit" name="htmlsubmitbutton2">Login</button>
</form>
Please remember, if a WHERE clause is added, the cross join behaves as an inner join. For example, the following Transact-SQL queries produce the same result set. Please refer to http://technet.microsoft.com/en-us/library/ms190690(v=sql.105).aspx
Another editor-based solution: text "rectangles" in Emacs.
Highlight the code you want to comment out, then C-x-r-t #
To un-comment the code: highlight, then C-x-r-k
I use this all-day, every day. (Assigned to hot-keys, of course.)
This and powerful regex search/replace is the reason I tolerate Emacs's other "eccentricities".
you could also specify multiple style values like this
$('#navigation ul li').css({'display': 'inline-block','background-color': '#ff0000', 'color': '#ffffff'});
Unfortunately this isn't entirely possible as the ClassLoader won't tell you what classes are available. You can, however, get fairly close doing something like this:
for (String classpathEntry : System.getProperty("java.class.path").split(System.getProperty("path.separator"))) {
if (classpathEntry.endsWith(".jar")) {
File jar = new File(classpathEntry);
JarInputStream is = new JarInputStream(new FileInputStream(jar));
JarEntry entry;
while( (entry = is.getNextJarEntry()) != null) {
if(entry.getName().endsWith(".class")) {
// Class.forName(entry.getName()) and check
// for implementation of the interface
}
}
}
}
Edit: johnstok is correct (in the comments) that this only works for standalone Java applications, and won't work under an application server.
If you want to get the full path of the directory of the current rb file:
File.expand_path('../', __FILE__)
You need to point to the directory instead. You must not specify the dockerfile.
docker build -t ubuntu-test:latest .
does work.
docker build -t ubuntu-test:latest ./Dockerfile
does not work.
Another thing to add, in the version I'm using, the code has to be initialized in order to be to comment it out using CTRL and / . If you haven't ran the code and the code isn't colorized it wont work.
Check Below Codes :
1. SynchronousRequest
Swift 1.2
let urlPath: String = "YOUR_URL_HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
var err: NSError
println(response)
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary
println("Synchronous\(jsonResult)")
Swift 2.0 +
let urlPath: String = "YOUR_URL_HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSURLRequest = NSURLRequest(URL: url)
let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
do{
let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)
print(response)
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
print("Synchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}catch let error as NSError
{
print(error.localizedDescription)
}
2. AsynchonousRequest
Swift 1.2
let urlPath: String = "YOUR_URL_HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("Asynchronous\(jsonResult)")
})
Swift 2.0 +
let urlPath: String = "YOUR_URL_HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSURLRequest = NSURLRequest(URL: url)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("ASynchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
})
3. As usual URL connection
Swift 1.2
var dataVal = NSMutableData()
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
Then
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.dataVal?.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!)
{
var error: NSErrorPointer=nil
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary
println(jsonResult)
}
Swift 2.0 +
var dataVal = NSMutableData()
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
Then
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
dataVal.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!)
{
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
4. Asynchronous POST Request
Swift 1.2
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "POST"
var stringPost="deviceToken=123456" // Key and Value
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request1.timeoutInterval = 60
request1.HTTPBody=data
request1.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("AsSynchronous\(jsonResult)")
})
Swift 2.0 +
let urlPath: String = "YOUR URL HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "POST"
let stringPost="deviceToken=123456" // Key and Value
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request1.timeoutInterval = 60
request1.HTTPBody=data
request1.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("ASynchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
})
5. Asynchronous GET Request
Swift 1.2
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "GET"
request1.timeoutInterval = 60
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("AsSynchronous\(jsonResult)")
})
Swift 2.0 +
let urlPath: String = "YOUR URL HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "GET"
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("ASynchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
})
6. Image(File) Upload
Swift 2.0 +
let mainURL = "YOUR_URL_HERE"
let url = NSURL(string: mainURL)
let request = NSMutableURLRequest(URL: url!)
let boundary = "78876565564454554547676"
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST" // POST OR PUT What you want
let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)
let imageData = UIImageJPEGRepresentation(UIImage(named: "Test.jpeg")!, 1)
var body = NSMutableData()
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// Append your parameters
body.appendData("Content-Disposition: form-data; name=\"name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("PREMKUMAR\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("IOS_DEVELOPER\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// Append your Image/File Data
var imageNameval = "HELLO.jpg"
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"profile_photo\"; filename=\"\(imageNameval)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData!)
body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
//handle error
}
else {
let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)!
print("Response:\(outputString)")
}
}
dataTask.resume()
7. GET,POST,Etc Swift 3.0 +
let request = NSMutableURLRequest(url: URL(string: "YOUR_URL_HERE" ,param: param))!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval:60)
request.httpMethod = "POST" // POST ,GET, PUT What you want
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("ASynchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
dataTask.resume()
Try use this.
char** strsplit(char* str, const char* delim){
char** res = NULL;
char* part;
int i = 0;
char* aux = strdup(str);
part = strdup(strtok(aux, delim));
while(part){
res = (char**)realloc(res, (i + 1) * sizeof(char*));
*(res + i) = strdup(part);
part = strdup(strtok(NULL, delim));
i++;
}
res = (char**)realloc(res, i * sizeof(char*));
*(res + i) = NULL;
return res;
}
Your code looks pretty good.
Be careful, however, for your call to Range("H5")
is a shortcut command to Application.Range("H5")
, which is equivalent to Application.ActiveSheet.Range("H5")
. This could be fine, if the only changes are user-changes -- which is the most typical -- but it is possible for the worksheet's cell values to change when it is not the active sheet via programmatic changes, e.g. VBA.
With this in mind, I would utilize Target.Worksheet.Range("H5")
:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Target.Worksheet.Range("H5")) Is Nothing Then Macro
End Sub
Or you can use Me.Range("H5")
, if the event handler is on the code page for the worksheet in question (it usually is):
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("H5")) Is Nothing Then Macro
End Sub
Hope this helps...
Try this code as below
var a = [5, 17, 29, 48, 64, 21];
function sortA(arr) {
return arr.sort(function(a, b) {
return a - b;
})
;}
alert(sortA(a));
Now a days, most of the sites add meta tags to their sites providing information about their site or any particular article page. Such as news or blog sites.
I have created a Meta API which gives you required meta data ac like OpenGraph, Schema.Org, etc.
Check it out - https://api.sakiv.com/docs
The dot operator .
does not need to be escaped inside of a character class []
.
Your second bit of code starts the first bit of code as a subprocess with piped input and output. It then closes its input and tries to read its output.
The first bit of code tries to read from standard input, but the process that started it closed its standard input, so it immediately reaches an end-of-file, which Python turns into an exception.
In my case I didn't add the http://
prefix. Potentially worth checking.
The bash for
consists on a variable (the iterator) and a list of words where the iterator will, well, iterate.
So, if you have a limited list of words, just put them in the following syntax:
for w in word1 word2 word3
do
doSomething($w)
done
Probably you want to iterate along some numbers, so you can use the seq
command to generate a list of numbers for you: (from 1 to 100 for example)
seq 1 100
and use it in the FOR loop:
for n in $(seq 1 100)
do
doSomething($n)
done
Note the $(...)
syntax. It's a bash behaviour, it allows you to pass the output from one command (in our case from seq
) to another (the for
)
This is really useful when you have to iterate over all directories in some path, for example:
for d in $(find $somepath -type d)
do
doSomething($d)
done
The possibilities are infinite to generate the lists.
I'm not sure if this has been said previously, or if it's what is needed here, but couldn't you make the string an array and then find the length?
let randomString = "Random String";
let stringWords = randomString.split(' ');
console.log(stringWords.length);
The general way to find any type is by example. The beauty of typescript is that you have access to all types, so long as you have the correct @types/
files.
To answer this myself I just thought of a component react uses that has the children
prop. The first thing that came to mind? How about a <div />
?
All you need to do is open vscode and create a new .tsx
file in a react project with @types/react
.
import React from 'react';
export default () => (
<div children={'test'} />
);
Hovering over the children
prop shows you the type. And what do you know -- Its type is ReactNode
(no need for ReactNode[]
).
Then if you click into the type definition it brings you straight to the definition of children
coming from DOMAttributes
interface.
// node_modules/@types/react/index.d.ts
interface DOMAttributes<T> {
children?: ReactNode;
...
}
Note: This process should be used to find any unknown type! All of them are there just waiting for you to find them :)
Maybe this is a good example of when to use nested classes?
// ORIGINAL
class ImageCacheSettings { }
class ImageCacheEntry { }
class ImageCache
{
ImageCacheSettings mSettings;
List<ImageCacheEntry> mEntries;
}
And:
// REFACTORED
class ImageCache
{
Settings mSettings;
List<Entry> mEntries;
class Settings {}
class Entry {}
}
PS: I've not taken into account which access modifiers should be applied (private, protected, public, internal)
To answer the second part of your question, to convert to binary you can use a format string and the ord
function:
>>> byte = 'a'
>>> '{0:08b}'.format(ord(byte))
'01100001'
Note that the format pads with the right number of leading zeros, which seems to be your requirement. This method needs Python 2.6 or later.
You can't... an array's size is always fixed in Java. Typically instead of using an array, you'd use an implementation of List<T>
here - usually ArrayList<T>
, but with plenty of other alternatives available.
You can create an array from the list as a final step, of course - or just change the signature of the method to return a List<T>
to start with.
read-host -assecurestring | convertfrom-securestring | out-file C:\securestring.txt
$pass = cat C:\securestring.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "test",$pass
$mycred.GetNetworkCredential().Password
Be very careful with storing passwords this way... it's not as secure as ...
Given an object which I suspect to be some kind of IList<>
, how can I determine of what it's an IList<>
?
Here's a reliable solution. My apologies for length - C#'s introspection API makes this suprisingly difficult.
/// <summary>
/// Test if a type implements IList of T, and if so, determine T.
/// </summary>
public static bool TryListOfWhat(Type type, out Type innerType)
{
Contract.Requires(type != null);
var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);
innerType = interfaceTest(type);
if (innerType != null)
{
return true;
}
foreach (var i in type.GetInterfaces())
{
innerType = interfaceTest(i);
if (innerType != null)
{
return true;
}
}
return false;
}
Example usage:
object value = new ObservableCollection<int>();
Type innerType;
TryListOfWhat(value.GetType(), out innerType).Dump();
innerType.Dump();
Returns
True
typeof(Int32)
There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.
Use dataType:"json"
for json
data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
I had the exact same problem running docker but I found the solution in the log preceding the error you've mentioned.
selenium_1 | 2016-11-11 11:19:34,498 DEBG 'xvfb' stderr output:
selenium_1 | (EE)
selenium_1 | Fatal server error:
selenium_1 | (EE) Server is already active for display 99
selenium_1 | If this server is no longer running, remove /tmp/.X99-lock
selenium_1 | and start again.
selenium_1 | (EE)
I've followed the advice and problem has been sorted out.
For docker-compose
you can use following docker-compose.yml
version: '2'
services:
nginx:
image: nginx
container_name: nginx-container
networks:
static-network:
ipv4_address: 172.20.128.2
networks:
static-network:
ipam:
config:
- subnet: 172.20.0.0/16
#docker-compose v3+ do not use ip_range
ip_range: 172.28.5.0/24
from host you can test using:
docker-compose up -d
curl 172.20.128.2
Modern docker-compose
does not change ip address that frequently.
To find ips of all containers in your docker-compose
in a single line use:
for s in `docker-compose ps -q`; do echo ip of `docker inspect -f "{{.Name}}" $s` is `docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $s`; done
If you want to automate, you can use something like this example gist
Two things
import os
dirpath = "<dirpath>" # Replace the "<dirpath>" with actual directory path.
if os.path.exists(dirpath):
print("Directory exist")
else: #this is optional if you want to create a directory if doesn't exist.
os.mkdir(dirpath):
print("Directory created")
I like Bjorn's answer, however the solution he's provided is misleading, as the method updates an existing parameter, rather than adding it if it doesn't exist.. To make it a bit safer, I've adapted it below.
public static class UriExtensions
{
/// <summary>
/// Adds or Updates the specified parameter to the Query String.
/// </summary>
/// <param name="url"></param>
/// <param name="paramName">Name of the parameter to add.</param>
/// <param name="paramValue">Value for the parameter to add.</param>
/// <returns>Url with added parameter.</returns>
public static Uri AddOrUpdateParameter(this Uri url, string paramName, string paramValue)
{
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
if (query.AllKeys.Contains(paramName))
{
query[paramName] = paramValue;
}
else
{
query.Add(paramName, paramValue);
}
uriBuilder.Query = query.ToString();
return uriBuilder.Uri;
}
}
$(document).ready(function(){
$('#category').change(function(){
$("#app").fadeOut();
$.ajax({
type: "POST",
url: "themes/ajax.php",
data: "cat="+$(this).val(),
cache: false,
success: function(msg)
{
$('#app').fadeIn().html(msg);
$('#app').change(function(){
$("#store").fadeOut();
$.ajax({
type: "POST",
url: "themes/ajax.php",
data: "app="+$(this).val(),
cache: false,
success: function(ms)
{
$('#store').fadeIn().html(ms);
}
});// second ajAx
});// second on change
}// first ajAx sucess
});// firs ajAx
});// firs on change
});
I was facing the same problem when import projects into IntelliJ.
for in my case first, check SDK details and check you have configured JDK correctly or not.
Go to File-> Project Structure-> platform Settings-> SDKs
Check your JDK is correct or not.
Next, I Removed project from IntelliJ and delete all IntelliJ and IDE related files and folder from the project folder (.idea, .settings, .classpath, dependency-reduced-pom). Also, delete the target folder and re-import the project.
The above solution worked in my case.
You can use GREATEST function with not nullable fields. If one of this values (or both) can be NULL, don't use it (result can be NULL).
select
if(
fieldA is NULL,
if(fieldB is NULL, NULL, fieldB), /* second NULL is default value */
if(fieldB is NULL, field A, GREATEST(fieldA, fieldB))
) as maxValue
You can change NULL to your preferred default value (if both values is NULL).
It is usually much faster to script out all the objects in the database, and create an empty one, that to delete from or truncate tables.
In my experience, I've had to leverage the event's currentTarget:
$("#dingus").click( function (event) {
if ($(event.currentTarget).is(':checked')) {
//checkbox is checked
}
});
You need to make sure your usercontrol hasn't set it's width in the usercontrol's xaml file. Just delete the Width="..." from it and you're good to go!
EDIT: This is the code I tested it with:
SOUserAnswerTest.xaml:
<UserControl x:Class="WpfApplication1.SOAnswerTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Name="LeftSideMenu" Width="100"/>
<ColumnDefinition Name="Middle" Width="*"/>
<ColumnDefinition Name="RightSideMenu" Width="90"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0">a</TextBlock>
<TextBlock Grid.Column="1">b</TextBlock>
<TextBlock Grid.Column="2">c</TextBlock>
</Grid>
</UserControl>
Window1.xaml:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="415">
<Grid>
<local:SOAnswerTest Grid.Column="0" Grid.Row="5" Grid.ColumnSpan="2"/>
</Grid>
</Window>
CreateImage(size, depth, channels)
https://opencv.willowgarage.com/documentation/python/core_operations_on_arrays.html#CreateImage
Execute the following command after installing and adding to the path
source ~/.bashrc
where source
is a bash shell built-in command that executes the content of the file passed as argument, in the current shell.
It runs during boot up automatically.
Objects are instances of classes. Classes are just the blueprints for objects. So given your class definition -
# Note the added (object) - this is the preferred way of creating new classes
class Student(object):
name = "Unknown name"
age = 0
major = "Unknown major"
You can create a make_student
function by explicitly assigning the attributes to a new instance of Student
-
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
return student
But it probably makes more sense to do this in a constructor (__init__
) -
class Student(object):
def __init__(self, name="Unknown name", age=0, major="Unknown major"):
self.name = name
self.age = age
self.major = major
The constructor is called when you use Student()
. It will take the arguments defined in the __init__
method. The constructor signature would now essentially be Student(name, age, major)
.
If you use that, then a make_student
function is trivial (and superfluous) -
def make_student(name, age, major):
return Student(name, age, major)
For fun, here is an example of how to create a make_student
function without defining a class. Please do not try this at home.
def make_student(name, age, major):
return type('Student', (object,),
{'name': name, 'age': age, 'major': major})()
Assuming you don't store things like the '+', '()', '-', spaces and what-have-yous (and why would you, they are presentational concerns which would vary based on local customs and the network distributions anyways), the ITU-T recommendation E.164 for the international telephone network (which most national networks are connected via) specifies that the entire number (including country code, but not including prefixes such as the international calling prefix necessary for dialling out, which varies from country to country, nor including suffixes, such as PBX extension numbers) be at most 15 characters.
Call prefixes depend on the caller, not the callee, and thus shouldn't (in many circumstances) be stored with a phone number. If the database stores data for a personal address book (in which case storing the international call prefix makes sense), the longest international prefixes you'd have to deal with (according to Wikipedia) are currently 5 digits, in Finland.
As for suffixes, some PBXs support up to 11 digit extensions (again, according to Wikipedia). Since PBX extension numbers are part of a different dialing plan (PBXs are separate from phone companies' exchanges), extension numbers need to be distinguishable from phone numbers, either with a separator character or by storing them in a different column.
One more option is to add the path of the privatekey file like this in terminal:
ssh-add "path to the privatekeyfile"
and then execute the pull command
GitLab 12.1 (July 2019) introduces a difference:
"Merge Requests for Confidential Issues"
When discussing, planning and resolving confidential issues, such as security vulnerabilities, it can be particularly challenging for open source projects to remain efficient since the Git repository is public.
As of 12.1, it is now possible for confidential issues in a public project to be resolved within a streamlined workflow using the Create confidential merge request button, which helps you create a merge request in a private fork of the project.
See "Confidential issues" from issue 58583.
A similar feature exists in GitHub, but involves the creation of a special private fork, called "maintainer security advisory".
GitLab 13.5 (Oct. 2020) will add reviewers, which was already available for GitHub before.
There is an open source program that I find online it uses openssl to encrypt and decrypt files. It does this with a single password. The great thing about this open source script is that it deletes the original unencrypted file by shredding the file. But the dangerous thing about is once the original unencrypted file is gone you have to make sure you remember your password otherwise they be no other way to decrypt your file.
Here the link it is on github
https://github.com/EgbieAnderson1/linux_file_encryptor/blob/master/file_encrypt.py
See http://wiki.apache.org/httpd/DistrosDefaultLayout for discussion of where you might find Apache httpd configuration files on various platforms, since this can vary from release to release and platform to platform. The most common answer, however, is either /etc/apache/conf or /etc/httpd/conf
Generically, you can determine the answer by running the command:
httpd -V
(That's a capital V). Or, on systems where httpd is renamed, perhaps apache2ctl -V
This will return various details about how httpd is built and configured, including the default location of the main configuration file.
One of the lines of output should look like:
-D SERVER_CONFIG_FILE="conf/httpd.conf"
which, combined with the line:
-D HTTPD_ROOT="/etc/httpd"
will give you a full path to the default location of the configuration file
Depending on the libc release it could be needed to set both SO_REUSEADDR and SO_REUSEPORT socket options as explained in socket(7) documentation :
SO_REUSEPORT (since Linux 3.9) Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. This option must be set on each socket (including the first socket) prior to calling bind(2) on the socket. To prevent port hijacking, all of the processes binding to the same address must have the same effective UID. This option can be employed with both TCP and UDP sockets.
As this socket option appears with kernel 3.9 and raspberry use 3.12.x, it will be needed to set SO_REUSEPORT.
You can set theses two options before calling bind like this :
int reuse = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");
#ifdef SO_REUSEPORT
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEPORT) failed");
#endif
Default c++ mechanism for file IO is called streams.
Streams can be of three flavors: input, output and inputoutput.
Input streams act like sources of data. To read data from an input stream you use >>
operator:
istream >> my_variable; //This code will read a value from stream into your variable.
Operator >>
acts different for different types. If in the example above my_variable
was an int, then a number will be read from the strem, if my_variable
was a string, then a word would be read, etc.
You can read more then one value from the stream by writing istream >> a >> b >> c;
where a, b and c would be your variables.
Output streams act like sink to which you can write your data. To write your data to a stream, use <<
operator.
ostream << my_variable; //This code will write a value from your variable into stream.
As with input streams, you can write several values to the stream by writing something like this:
ostream << a << b << c;
Obviously inputoutput streams can act as both.
In your code sample you use cout
and cin
stream objects.
cout
stands for console-output and cin for console-input
. Those are predefined streams for interacting with default console.
To interact with files, you need to use ifstream
and ofstream
types.
Similar to cin
and cout
, ifstream
stands for input-file-stream
and ofstream
stands for output-file-stream
.
Your code might look like this:
#include <iostream>
#include <fstream>
using namespace std;
int start()
{
cout << "Welcome...";
// do fancy stuff
return 0;
}
int main ()
{
string usreq, usr, yn, usrenter;
cout << "Is this your first time using TEST" << endl;
cin >> yn;
if (yn == "y")
{
ifstream iusrfile;
ofstream ousrfile;
iusrfile.open("usrfile.txt");
iusrfile >> usr;
cout << iusrfile; // I'm not sure what are you trying to do here, perhaps print iusrfile contents?
iusrfile.close();
cout << "Please type your Username. \n";
cin >> usrenter;
if (usrenter == usr)
{
start ();
}
}
else
{
cout << "THAT IS NOT A REGISTERED USERNAME.";
}
return 0;
}
For further reading you might want to look at c++ I/O reference
<div id="canvasdiv" style="margin: 5px; height: 100%; width: 100%;">
<canvas id="mycanvas" style="border: 1px solid red;"></canvas>
</div>
<script>
$(function(){
InitContext();
});
function InitContext()
{
var $canvasDiv = $('#canvasdiv');
var canvas = document.getElementById("mycanvas");
canvas.height = $canvasDiv.innerHeight();
canvas.width = $canvasDiv.innerWidth();
}
</script>
You can also use the Pivot Keyword if you are using SQL 2005 or above
SELECT *
FROM @Users
PIVOT (
COUNT(Position)
FOR Position
IN (Manager, CEO, Employee)
) as p
Test Data Set
DECLARE @Users TABLE (Position VARCHAR(10))
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('CEO')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
<form method="POST" action="chk_kw.php">
<select name="website_string">
<option selected="selected"></option>
<option value="abc">abc</option>
<option value="def">def</option>
<option value="hij">hij</option>
</select>
<input type="submit">
</form>
print_r($_POST);
,
it'll show what's being submitted an the respective element name.To get the submitted value of the element in question do:
$website_string = $_POST['website_string'];
Aangular 2 final has updated APIs. They have added many methods for this.
To update the form control from controller do this:
this.form.controls['dept'].setValue(selected.id);
this.form.controls['dept'].patchValue(selected.id);
No need to reset the errors
References
https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html
https://toddmotto.com/angular-2-form-controls-patch-value-set-value
With new git difftool, its as simple as adding this to your .gitconfig file:
[diff]
tool = any-name
[difftool "any-name"]
cmd = "\"C:/path/to/my/ext/diff.exe\" \"$LOCAL\" \"$REMOTE\""
Optionally, also add:
[difftool]
prompt = false
Also check out diffall, a simple script I wrote to extend the annoying (IMO) default diff behaviour of opening each in serial.
Global .gitconfig on Windows is in %USERPROFILE%\.gitconfig
cpdf will do the job from the command-line. It isn't python, though (afaik):
cpdf -add-text "Line of text" input.pdf -o output .pdf
Your syntax is fine, it will return rows where LastAdDate
lies within the last 6 months;
select cast('01-jan-1970' as datetime) as LastAdDate into #PubAdvTransData
union select GETDATE()
union select NULL
union select '01-feb-2010'
DECLARE @sp_Date DATETIME = DateAdd(m, -6, GETDATE())
SELECT * FROM #PubAdvTransData pat
WHERE (pat.LastAdDate > @sp_Date)
>2010-02-01 00:00:00.000
>2010-04-29 21:12:29.920
Are you sure LastAdDate
is of type DATETIME
?
Go to magento/var/report
and open the file with the Error log record number name i.e 673618173351
in your case. In that file you can find the complete description of the error.
For log files like system.log
and exception.log
, go to magento/var/log/
.
Fatal error: Out of memory (allocated SOLVED
i had similar problem, for months no solution. finally i was checking in one of the apache folders i.e(\apache\conf\extra) i came across this file that controls the memory allocation of apache. the file name is httpd-mpm in that file you are to increase the MaxMemFree which is set 2048 to something higher, i took mine to 10000 for the first MaxMemFree (IfModule !mpm_netware_module) then made the second one MaxMemFree to 5000 IfModule mpm_netware_module.
These solved my problem. hope it helps
This works:
<div id="start-element">Click Me</div>
$(document).on("click","#test-element",function() {
alert("click");
});
$(document).on("click","#start-element",function() {
$(this).attr("id", "test-element");
});
Here is the Fiddle
If your text is in a Bash variable, then Parameter Substitution ${var//\\//}
can replace substrings:
$ p='C:\foo\bar.xml'
$ printf '%s\n' "$p"
C:\foo\bar.xml
$ printf '%s\n' "${p//\\//}"
C:/foo/bar.xml
This may be leaner and clearer that filtering through a command such as tr
or sed
.
I tried the code:
tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
In the viewDidLoad section and xcode6 showed a warning. I have put a "self." in front of it and now it works fine. so the working code I use is:
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
just mention that - Jan, 2020 Xcode 11.3/iOS13
Swift 5
From the CoreGraphics source code
public struct CGFloat {
/// The native type used to store the CGFloat, which is Float on
/// 32-bit architectures and Double on 64-bit architectures.
public typealias NativeType = Double
In PowerShell v5+, there is an Expand-Archive command (as well as Compress-Archive) built in:
Expand-Archive c:\a.zip -DestinationPath c:\a
Inside of your <head></head>
tags add...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('input[type=radio]').change(function() {
$('input[type=radio]').each(function(index) {
$(this).closest('tr').removeClass('selected');
});
$(this).closest('tr').addClass('selected');
});
});
</script>
EDIT: The placement inside of <head></head>
is not the only option...this could just as easily be placed RIGHT before the closing </body>
tag. I generally try and place my JavaScript inside of head
for placement reasons, but it can in some cases slow down page rendering so some will recommend the latter approach (before closing body
).
A simple program's compilation workflow is simple, I can draw it as a small graph: source -> [compilation] -> object [linking] -> executable. There are files (source, object, executable) in this graph, and rules (make's terminology). That graph is definied in the Makefile.
When you launch make, it reads Makefile, and checks for changed files. If there's any, it triggers the rule, which depends on it. The rule may produce/update further files, which may trigger other rules and so on. If you create a good makefile, only the necessary rules (compiler/link commands) will run, which stands "to next" from the modified file in the dependency path.
Pick an example Makefile, read the manual for syntax (anyway, it's clear for first sight, w/o manual), and draw the graph. You have to understand compiler options in order to find out the names of the result files.
The make graph should be as complex just as you want. You can even do infinite loops (don't do)! You can tell make, which rule is your target, so only the left-standing files will be used as triggers.
Again: draw the graph!.
If you using on input tag than this code will help you. I write this code by myself and I think this is very good way to use in input. but you can change it using your format. It will help user to correct their format on input tag.
$("#phone").on('input', function() { //this is use for every time input change.
var inputValue = getInputValue(); //get value from input and make it usefull number
var length = inputValue.length; //get lenth of input
if (inputValue < 1000)
{
inputValue = '1('+inputValue;
}else if (inputValue < 1000000)
{
inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, length);
}else if (inputValue < 10000000000)
{
inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, 6) + '-' + inputValue.substring(6, length);
}else
{
inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, 6) + '-' + inputValue.substring(6, 10);
}
$("#phone").val(inputValue); //correct value entered to your input.
inputValue = getInputValue();//get value again, becuase it changed, this one using for changing color of input border
if ((inputValue > 2000000000) && (inputValue < 9999999999))
{
$("#phone").css("border","black solid 1px");//if it is valid phone number than border will be black.
}else
{
$("#phone").css("border","red solid 1px");//if it is invalid phone number than border will be red.
}
});
function getInputValue() {
var inputValue = $("#phone").val().replace(/\D/g,''); //remove all non numeric character
if (inputValue.charAt(0) == 1) // if first character is 1 than remove it.
{
var inputValue = inputValue.substring(1, inputValue.length);
}
return inputValue;
}
You can use the storage_path();
function to get storage folder path.
storage_path(); // Return path like: laravel_app\storage
Suppose you want to save your logfile mylog.log
inside Log folder of storage folder. You have to write something like
storage_path() . '/LogFolder/mylog.log'
You can repaint and / or requery:
On the close event of form B:
Forms!FormA.Requery
Is this what you mean?
mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64
You may need to try the following
yum install php-mysql-5.3.3-40.el6_6.x86_64
EDIT: as_matrix
is deprecated since version 0.23.0
You can use the built in values
or to_numpy
(recommended option) method on the dataframe:
In [8]:
df.to_numpy()
Out[8]:
array([[ 0.9, 7. , 5.2, ..., 13.3, 13.5, 8.9],
[ 0.9, 7. , 5.2, ..., 13.3, 13.5, 8.9],
[ 0.8, 6.1, 5.4, ..., 15.9, 14.4, 8.6],
...,
[ 0.2, 1.3, 2.3, ..., 16.1, 16.1, 10.8],
[ 0.2, 1.3, 2.4, ..., 16.5, 15.9, 11.4],
[ 0.2, 1.3, 2.4, ..., 16.5, 15.9, 11.4]])
If you explicitly want lists and not a numpy array add .tolist()
:
df.to_numpy().tolist()
You can use the listings package. It supports many different languages and there are lots of options for customising the output.
\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[language=html]
<html>
<head>
<title>Hello</title>
</head>
<body>Hello</body>
</html>
\end{lstlisting}
\end{document}
public void printList(ArrayList<Address> list){
for(Address elem : list){
System.out.println(elem+" ");
}
}
Crossframe-Scripting is not possible when the two frames have different domains -> Security.
See this: http://javascript.about.com/od/reference/a/frame3.htm
Now to answer your question: there is no solution or work around, you simply should check your website-design why there must be two frames from different domains that changes the url of the other one.
public string phoneformat(string phnumber)
{
String phone=phnumber;
string countrycode = phone.Substring(0, 3);
string Areacode = phone.Substring(3, 3);
string number = phone.Substring(6,phone.Length);
phnumber="("+countrycode+")" +Areacode+"-" +number ;
return phnumber;
}
Output will be :001-568-895623
One also may use the following to catch the errors:
$.ajax({
url: url,
success: function (data) {
// Handle success here
$('#editor-content-container').html(data);
$('#editor-container').modal('show');
},
cache: false
}).fail(function (jqXHR, textStatus, error) {
// Handle error here
$('#editor-content-container').html(jqXHR.responseText);
$('#editor-container').modal('show');
});
It's browser dependent. "By default, Internet Explorer has a KeepAliveTimeout value of one minute and an additional limiting factor (ServerInfoTimeout) of two minutes. Either setting can cause Internet Explorer to reset the socket." - from IE support http://support.microsoft.com/kb/813827
Firefox is around the same value I think as well.
Usually though server timeout are set lower than browser timeouts, but at least you can control that and set it higher.
You'd rather handle the timeout though, so that way you can act upon such an event. See this thread: How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?
Enabled Blaze and it still doesn't work?
Most probably you need to set .env
from the right path, require('dotenv').config({ path: __dirname + './../.env' });
won't work (or any other path). Simply put the .env
file in the functions
directory, from which you deploy to Firebase
.
If you want to use something similar to the JavaScript, you just need to convert to strings first:
Console.WriteLine(mon.ToString() + "." + da.ToString() + "." + yer.ToString());
But a (much) better way would be to use the format option:
Console.WriteLine("{0}.{1}.{2}", mon, da, yer);
If you want to do a horizontal centering, just put the form inside a DIV tag and apply align="center" attribute to it. So even if the form width is changed, your centering will remain the same.
<div align="center"><form id="form_login"><!--form content here--></form></div>
UPDATE
@G-Cyr is right. align="center"
attribute is now obsolete. You can use text-align
attribute for this as following.
<div style="text-align:center"><form id="form_login"><!--form content here--></form></div>
This will center all the content inside the parent DIV. An optional way is to use margin: auto
CSS attribute with predefined widths and heights. Please follow the following thread for more information.
How to horizontally center a in another ?
Vertical centering is little difficult than that. To do that, you can do the following stuff.
html
<body>
<div id="parent">
<form id="form_login">
<!--form content here-->
</form>
</div>
</body>
Css
#parent {
display: table;
width: 100%;
}
#form_login {
display: table-cell;
text-align: center;
vertical-align: middle;
}
# Pseudo code
# Corners in ax,ay,bx,by,dx,dy
# Point in x, y
bax = bx - ax
bay = by - ay
dax = dx - ax
day = dy - ay
if ((x - ax) * bax + (y - ay) * bay < 0.0) return false
if ((x - bx) * bax + (y - by) * bay > 0.0) return false
if ((x - ax) * dax + (y - ay) * day < 0.0) return false
if ((x - dx) * dax + (y - dy) * day > 0.0) return false
return true
I discovered while following the above suggestions that for line in f: does not work for a pandas dataframe (not that anyone said it would) because the end of file in a dataframe is the last column, not the last row. for example if you have a data frame with 3 fields (columns) and 9 records (rows), the for loop will stop after the 3rd iteration, not after the 9th iteration. Teresa
Answer is chmod 755 hello - it makes file executable... It is funny, so no-one answered it. I had same problem on MacOS, which is now solved.
nano hello.c make hello chmod 755 hello Then you run it by ./hello
clang --version Apple LLVM version 8.0.0 (clang-800.0.42.1) Target: x86_64-apple-darwin15.6.0
nothing was installed, nano make (clang) chmod - all inside MacOS already
I too got this problem and all solutions given above either failed or were not applicable due to client webservice restrictions.
For this, I added an iframe in my page which resided in the client;s server. So when we post our data to the iframe and the iframe then posts it to the webservice. Hence the cross-domain referencing is eliminated.
We added a 2-way origin check to confirm only authorized page posts data to and from the iframe.
Hope it helps
<iframe style="display:none;" id='receiver' name="receiver" src="https://iframe-address-at-client-server">
</iframe>
//send data to iframe
var hiddenFrame = document.getElementById('receiver').contentWindow;
hiddenFrame.postMessage(JSON.stringify(message), 'https://client-server-url');
//The iframe receives the data using the code:
window.onload = function () {
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function (e) {
var origin = e.origin;
//if origin not in pre-defined list, break and return
var messageFromParent = JSON.parse(e.data);
var json = messageFromParent.data;
//send json to web service using AJAX
//return the response back to source
e.source.postMessage(JSON.stringify(aJAXResponse), e.origin);
}, false);
}
The problem is that multiprocessing must pickle things to sling them among processes, and bound methods are not picklable. The workaround (whether you consider it "easy" or not;-) is to add the infrastructure to your program to allow such methods to be pickled, registering it with the copy_reg standard library method.
For example, Steven Bethard's contribution to this thread (towards the end of the thread) shows one perfectly workable approach to allow method pickling/unpickling via copy_reg
.
Short function. PHP 5.3 and up. Can take optional third param of any date format that strtotime can understand. Automatically reverses direction if end < start.
function getDatesFromRange($start, $end, $format='Y-m-d') {
return array_map(function($timestamp) use($format) {
return date($format, $timestamp);
},
range(strtotime($start) + ($start < $end ? 4000 : 8000), strtotime($end) + ($start < $end ? 8000 : 4000), 86400));
}
Test:
date_default_timezone_set('Europe/Berlin');
print_r(getDatesFromRange( '2016-7-28','2016-8-2' ));
print_r(getDatesFromRange( '2016-8-2','2016-7-28' ));
print_r(getDatesFromRange( '2016-10-28','2016-11-2' ));
print_r(getDatesFromRange( '2016-11-2','2016-10-28' ));
print_r(getDatesFromRange( '2016-4-2','2016-3-25' ));
print_r(getDatesFromRange( '2016-3-25','2016-4-2' ));
print_r(getDatesFromRange( '2016-8-2','2016-7-25' ));
print_r(getDatesFromRange( '2016-7-25','2016-8-2' ));
Output:
Array ( [0] => 2016-07-28 [1] => 2016-07-29 [2] => 2016-07-30 [3] => 2016-07-31 [4] => 2016-08-01 [5] => 2016-08-02 )
Array ( [0] => 2016-08-02 [1] => 2016-08-01 [2] => 2016-07-31 [3] => 2016-07-30 [4] => 2016-07-29 [5] => 2016-07-28 )
Array ( [0] => 2016-10-28 [1] => 2016-10-29 [2] => 2016-10-30 [3] => 2016-10-31 [4] => 2016-11-01 [5] => 2016-11-02 )
Array ( [0] => 2016-11-02 [1] => 2016-11-01 [2] => 2016-10-31 [3] => 2016-10-30 [4] => 2016-10-29 [5] => 2016-10-28 )
Array ( [0] => 2016-04-02 [1] => 2016-04-01 [2] => 2016-03-31 [3] => 2016-03-30 [4] => 2016-03-29 [5] => 2016-03-28 [6] => 2016-03-27 [7] => 2016-03-26 [8] => 2016-03-25 )
Array ( [0] => 2016-03-25 [1] => 2016-03-26 [2] => 2016-03-27 [3] => 2016-03-28 [4] => 2016-03-29 [5] => 2016-03-30 [6] => 2016-03-31 [7] => 2016-04-01 [8] => 2016-04-02 )
Array ( [0] => 2016-08-02 [1] => 2016-08-01 [2] => 2016-07-31 [3] => 2016-07-30 [4] => 2016-07-29 [5] => 2016-07-28 [6] => 2016-07-27 [7] => 2016-07-26 [8] => 2016-07-25 )
Array ( [0] => 2016-07-25 [1] => 2016-07-26 [2] => 2016-07-27 [3] => 2016-07-28 [4] => 2016-07-29 [5] => 2016-07-30 [6] => 2016-07-31 [7] => 2016-08-01 [8] => 2016-08-02 )
<!DOCTYPE html>
<html>
<head>
<title>aj</title>
</head>
<body>
<canvas id="c"></canvas>
</body>
</html>
with CSS
body {
margin: 0;
padding: 0
}
#c {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden
}
if you just want to stopping insecure warning like:
/usr/lib/python3/dist-packages/urllib3/connectionpool.py:794: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html InsecureRequestWarning)
do:
requests.METHOD("https://www.google.com", verify=False)
verify=False
is the key, followings are not good at it:
requests.packages.urllib3.disable_warnings()
or
urllib3.disable_warnings()
but, you HAVE TO know, that might cause potential security risks.
import subprocess
import os
'''
servers.txt contains ip address in following format
192.168.1.1
192.168.1.2
'''
with open('servers.txt', 'r') as f:
for ip in f:
result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip],stdout=f, stderr=f).wait()
if result:
print(ip, "inactive")
else:
print(ip, "active")
It's probably not what you want, but a tool like re2c can compile POSIX(-ish) regular expressions to ANSI C. It's written as a replacement for lex
, but this approach allows you to sacrifice flexibility and legibility for the last bit of speed, if you really need it.
In my case, I had already generated an APK file using the command ionic cordova build android --prod
and I needed to get the SHA-1 fingerprint for the already existing APK file. Here's how I got it by running the following command in the App directory:
keytool -list -printcert -jarfile app-debug.apk
So, I basically ran the above command in the following app location:
C:\myApp\platforms\android\app\build\outputs\apk\debug>keytool -list -printcert -jarfile app-debug.apk
This gave me the SHA1 fingerprint as: 7B:6B:AD:...
Hope this helps someone!
I use: /drawable/circulo.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:angle="270"
android:color="@color/your_color" />
</shape>
And then I use it in my TextView as:
android:background="@drawable/circulo"
no need to complicated it.
If nothing worked use git rm filename to delete file from disk and add it back.
In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged
event:
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
// Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
// To work around this, we create the binding once we get the viewmodel through the datacontext.
var newViewModel = e.NewValue as MyViewModel;
var executablePathBinding = new Binding
{
Source = newViewModel,
Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
};
BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}
We have also had cases were we just saved the DataContext
to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext
around, I think it would be nice to also call:
BindingOperations.ClearBinding(myText, TextBlock.TextProperty);
to clear the binding of the old viewmodel (e.oldValue
in the event handler).
You can use this IE HTML5 shim script to gain a basic level of support for the new semantic elements in HTML5 such as <article>
.
"What is it?" and "What does it do?" has been explained above.
I will give a example of "when it should be used".
For example, we have a class with lots of resource like big array in it.
class ResHeavy{ // ResHeavy means heavy resource
public:
ResHeavy(int len=10):_upInt(new int[len]),_len(len){
cout<<"default ctor"<<endl;
}
ResHeavy(const ResHeavy& rhs):_upInt(new int[rhs._len]),_len(rhs._len){
cout<<"copy ctor"<<endl;
}
ResHeavy& operator=(const ResHeavy& rhs){
_upInt.reset(new int[rhs._len]);
_len = rhs._len;
cout<<"operator= ctor"<<endl;
}
ResHeavy(ResHeavy&& rhs){
_upInt = std::move(rhs._upInt);
_len = rhs._len;
rhs._len = 0;
cout<<"move ctor"<<endl;
}
// check array valid
bool is_up_valid(){
return _upInt != nullptr;
}
private:
std::unique_ptr<int[]> _upInt; // heavy array resource
int _len; // length of int array
};
Test code:
void test_std_move2(){
ResHeavy rh; // only one int[]
// operator rh
// after some operator of rh, it becomes no-use
// transform it to other object
ResHeavy rh2 = std::move(rh); // rh becomes invalid
// show rh, rh2 it valid
if(rh.is_up_valid())
cout<<"rh valid"<<endl;
else
cout<<"rh invalid"<<endl;
if(rh2.is_up_valid())
cout<<"rh2 valid"<<endl;
else
cout<<"rh2 invalid"<<endl;
// new ResHeavy object, created by copy ctor
ResHeavy rh3(rh2); // two copy of int[]
if(rh3.is_up_valid())
cout<<"rh3 valid"<<endl;
else
cout<<"rh3 invalid"<<endl;
}
output as below:
default ctor
move ctor
rh invalid
rh2 valid
copy ctor
rh3 valid
We can see that std::move
with move constructor
makes transform resource easily.
Where else is std::move
useful?
std::move
can also be useful when sorting an array of elements. Many sorting algorithms (such as selection sort and bubble sort) work by swapping pairs of elements. Previously, we’ve had to resort to copy-semantics to do the swapping. Now we can use move semantics, which is more efficient.
It can also be useful if we want to move the contents managed by one smart pointer to another.
Cited:
If you are Using HTML5 you can add the attribute 'download' to your links.
<a href="/test.pdf" download>
To get the index
values as a list
/list
of tuple
s for Index
/MultiIndex
do:
df.index.values.tolist() # an ndarray method, you probably shouldn't depend on this
or
list(df.index.values) # this will always work in pandas
For center horizontally Just put
#over img {
display: block;
margin: 0 auto;
clear:both;
}
Another method:
#over img {
display: inline-block;
text-align: center;
}
For center vertically Just put:
#over img {
vertical-align: middle;
}
To use the array type properly as a function argument or template parameter, make a struct instead of a typedef, then add an operator[]
to the struct so you can keep the array like functionality like so:
typedef struct type24 {
char& operator[](int i) { return byte[i]; }
char byte[3];
} type24;
type24 x;
x[2] = 'r';
char c = x[2];
Based on @Ted's answer, I've used this extension:
extension XCTestCase {
// Based on https://stackoverflow.com/a/33855219
func waitFor<T>(object: T, timeout: TimeInterval = 5, file: String = #file, line: UInt = #line, expectationPredicate: @escaping (T) -> Bool) {
let predicate = NSPredicate { obj, _ in
expectationPredicate(obj as! T)
}
expectation(for: predicate, evaluatedWith: object, handler: nil)
waitForExpectations(timeout: timeout) { error in
if (error != nil) {
let message = "Failed to fulful expectation block for \(object) after \(timeout) seconds."
let location = XCTSourceCodeLocation(filePath: file, lineNumber: line)
let issue = XCTIssue(type: .assertionFailure, compactDescription: message, detailedDescription: nil, sourceCodeContext: .init(location: location), associatedError: nil, attachments: [])
self.record(issue)
}
}
}
}
You can use it like this
let element = app.staticTexts["Name of your element"]
waitFor(object: element) { $0.exists }
It also allows for waiting for an element to disappear, or any other property to change (by using the appropriate block)
waitFor(object: element) { !$0.exists } // Wait for it to disappear
Illegal XML Tag Name Characters can be encoded using Unicode UCS-2. This works very nicely. I am using it to create XML that gets turned into json (JPath is weak compared to XPath). Notice the handling of spaces, (, ) characters. Unicode UCS-2 Code Chart: http://www.columbia.edu/kermit/ucs2.html
tag.Name = tag.Name.Replace(" ", "_x005F_x0020_");
tag.Name = tag.Name.Replace("(", "_x005F_x0028_");
tag.Name = tag.Name.Replace(")", "_x005F_x0029_");
XML:
<Internal_x005F_x0020_Chargeback_x005F_x0020_ID>{CHARGEBACKCODE}</Internal_x005F_x0020_Chargeback_x005F_x0020_ID>
<Bill_x005F_x0020_To>{CHARGEBACKCODE}</Bill_x005F_x0020_To>
<Operator_x005F_x0020_or_x005F_x0020_Directly_x005F_x0020_Responsible_x005F_x0020_Individual_x005F_x0020__x005F_x0028_DRI_x005F_x0029_>[email protected]</Operator_x005F_x0020_or_x005F_x0020_Directly_x005F_x0020_Responsible_x005F_x0020_Individual_x005F_x0020__x005F_x0028_DRI_x005F_x0029_>
transformed to json via json.net:
"Internal Chargeback ID": "{CHARGEBACKCODE}",
"Bill To": "{CHARGEBACKCODE}",
"Operator or Directly Responsible Individual (DRI)": "[email protected]",
If you are using a Form Control
, you can get the same property as ActiveX
by using OLEFormat.Object
property of the Shape Object
. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.
Dim opt As OptionButton
With Sheets("Sheet1") ' Try to be always explicit
Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With
But then again, you really don't need to know the value.
If you use Form Control
, you associate a Macro
or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.
For example you have 2 Form Control
Option Buttons.
Sub CheckOptions()
Select Case Application.Caller
Case "Option Button 1"
' Action for option button 1
Case "Option Button 2"
' Action for option button 2
End Select
End Sub
In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller
.
This way, no need to check whether the option button value is true or false.
This worked for me.
First of all give the view controller in your storyboard a Storyboard ID inside the identity inspector. Then use the following example code (ensuring the class, storyboard name and story board ID match those that you are using):
let viewController:
UIViewController = UIStoryboard(
name: "Main", bundle: nil
).instantiateViewControllerWithIdentifier("ViewController") as UIViewController
// .instantiatViewControllerWithIdentifier() returns AnyObject!
// this must be downcast to utilize it
self.presentViewController(viewController, animated: false, completion: nil)
For more details see http://sketchytech.blogspot.com/2012/11/instantiate-view-controller-using.html best wishes
In URL as UI Jakob Nielsen recommends:
the social interface to the Web relies on email when users want to recommend Web pages to each other, and email is the second-most common way users get to new sites (search engines being the most common): make sure that all URLs on your site are less than 78 characters long so that they will not wrap across a line feed.
This is not the maximum but I'd consider this a practical maximum if you want your URL to be shared.
nametext
is an std::string
but these do not have the stream insertion operator (<<
) like output streams do.
To concatenate strings you can use the append
member function (or its equivalent, +=
, which works in the exact same way) or the +
operator, which creates a new string as a result of concatenating the previous two.
In Java there is no direct way to get browser and OS related information.
But to get this few third-party tools are available.
Instead of trusting third-party tools, I suggest you to parse the user agent.
String browserDetails = request.getHeader("User-Agent");
By doing this you can separate the browser details and OS related information easily according to your requirement. PFB the snippet for reference.
String browserDetails = request.getHeader("User-Agent");
String userAgent = browserDetails;
String user = userAgent.toLowerCase();
String os = "";
String browser = "";
log.info("User Agent for the request is===>"+browserDetails);
//=================OS=======================
if (userAgent.toLowerCase().indexOf("windows") >= 0 )
{
os = "Windows";
} else if(userAgent.toLowerCase().indexOf("mac") >= 0)
{
os = "Mac";
} else if(userAgent.toLowerCase().indexOf("x11") >= 0)
{
os = "Unix";
} else if(userAgent.toLowerCase().indexOf("android") >= 0)
{
os = "Android";
} else if(userAgent.toLowerCase().indexOf("iphone") >= 0)
{
os = "IPhone";
}else{
os = "UnKnown, More-Info: "+userAgent;
}
//===============Browser===========================
if (user.contains("msie"))
{
String substring=userAgent.substring(userAgent.indexOf("MSIE")).split(";")[0];
browser=substring.split(" ")[0].replace("MSIE", "IE")+"-"+substring.split(" ")[1];
} else if (user.contains("safari") && user.contains("version"))
{
browser=(userAgent.substring(userAgent.indexOf("Safari")).split(" ")[0]).split("/")[0]+"-"+(userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1];
} else if ( user.contains("opr") || user.contains("opera"))
{
if(user.contains("opera"))
browser=(userAgent.substring(userAgent.indexOf("Opera")).split(" ")[0]).split("/")[0]+"-"+(userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1];
else if(user.contains("opr"))
browser=((userAgent.substring(userAgent.indexOf("OPR")).split(" ")[0]).replace("/", "-")).replace("OPR", "Opera");
} else if (user.contains("chrome"))
{
browser=(userAgent.substring(userAgent.indexOf("Chrome")).split(" ")[0]).replace("/", "-");
} else if ((user.indexOf("mozilla/7.0") > -1) || (user.indexOf("netscape6") != -1) || (user.indexOf("mozilla/4.7") != -1) || (user.indexOf("mozilla/4.78") != -1) || (user.indexOf("mozilla/4.08") != -1) || (user.indexOf("mozilla/3") != -1) )
{
//browser=(userAgent.substring(userAgent.indexOf("MSIE")).split(" ")[0]).replace("/", "-");
browser = "Netscape-?";
} else if (user.contains("firefox"))
{
browser=(userAgent.substring(userAgent.indexOf("Firefox")).split(" ")[0]).replace("/", "-");
} else if(user.contains("rv"))
{
browser="IE-" + user.substring(user.indexOf("rv") + 3, user.indexOf(")"));
} else
{
browser = "UnKnown, More-Info: "+userAgent;
}
log.info("Operating System======>"+os);
log.info("Browser Name==========>"+browser);
I had the exact same problem. The way I solved it on Mac is this:
I didn't really like any of the solutions here for my particular use case, so I figured I'd post what I did because I didn't see it here.
I simply wanted to use a controller more like a directive, within a ng-repeat loop:
<div ng-repeat="objParameter in [{id:'a'},{id:'b'},{id:'c'}]">
<div ng-controller="DirectiveLikeController as ctrl"></div>
</div>
Now, in order to access the objParameter
on creation within each DirectiveLikeController (or to get the up-to-date objParameter at ANY time), all I need to do is inject $scope and call $scope.$eval('objParameter')
:
var app = angular.module('myapp', []);
app.controller('DirectiveLikeController',['$scope'], function($scope) {
//print 'a' for the 1st instance, 'b' for the 2nd instance, and 'c' for the 3rd.
console.log($scope.$eval('objParameter').id);
});
The only real downside that I see is that it requires the parent controller to know that the parameter is named objParameter
.
If you are using any spreadsheet application there is a basic function if()
with syntax:
if(<condition>, <yes>, <no>)
Syntax is exactly the same for ifelse()
in R:
ifelse(<condition>, <yes>, <no>)
The only difference to if()
in spreadsheet application is that R ifelse()
is vectorized (takes vectors as input and return vector on output). Consider the following comparison of formulas in spreadsheet application and in R for an example where we would like to compare if a > b and return 1 if yes and 0 if not.
In spreadsheet:
A B C
1 3 1 =if(A1 > B1, 1, 0)
2 2 2 =if(A2 > B2, 1, 0)
3 1 3 =if(A3 > B3, 1, 0)
In R:
> a <- 3:1; b <- 1:3
> ifelse(a > b, 1, 0)
[1] 1 0 0
ifelse()
can be nested in many ways:
ifelse(<condition>, <yes>, ifelse(<condition>, <yes>, <no>))
ifelse(<condition>, ifelse(<condition>, <yes>, <no>), <no>)
ifelse(<condition>,
ifelse(<condition>, <yes>, <no>),
ifelse(<condition>, <yes>, <no>)
)
ifelse(<condition>, <yes>,
ifelse(<condition>, <yes>,
ifelse(<condition>, <yes>, <no>)
)
)
To calculate column idnat2
you can:
df <- read.table(header=TRUE, text="
idnat idbp idnat2
french mainland mainland
french colony overseas
french overseas overseas
foreign foreign foreign"
)
with(df,
ifelse(idnat=="french",
ifelse(idbp %in% c("overseas","colony"),"overseas","mainland"),"foreign")
)
What is the condition has length > 1 and only the first element will be used
? Let's see:
> # What is first condition really testing?
> with(df, idnat=="french")
[1] TRUE TRUE TRUE FALSE
> # This is result of vectorized function - equality of all elements in idnat and
> # string "french" is tested.
> # Vector of logical values is returned (has the same length as idnat)
> df$idnat2 <- with(df,
+ if(idnat=="french"){
+ idnat2 <- "xxx"
+ }
+ )
Warning message:
In if (idnat == "french") { :
the condition has length > 1 and only the first element will be used
> # Note that the first element of comparison is TRUE and that's whay we get:
> df
idnat idbp idnat2
1 french mainland xxx
2 french colony xxx
3 french overseas xxx
4 foreign foreign xxx
> # There is really logic in it, you have to get used to it
Can I still use if()
? Yes, you can, but the syntax is not so cool :)
test <- function(x) {
if(x=="french") {
"french"
} else{
"not really french"
}
}
apply(array(df[["idnat"]]),MARGIN=1, FUN=test)
If you are familiar with SQL, you can also use CASE
statement in sqldf
package.
The simplest solution is to apply Python str
function to the column you are trying to loop through.
If you are using pandas
, this can be implemented as:
dataframe['column_name']=dataframe['column_name'].apply(str)
Syntax:
controlName.CssClass="CSS Class Name";
Example:
txtBank.CssClass = "csError";
Updated.. I solved this issue by stating the charset on PDO connection as below:
"mysql:host=$host;dbname=$db;charset=utf8"
All data received was then in the correct charset for the rest of the code to use
Use below code to convert String Date to Epoc Timestamp. Note : - Your input Date format should match with SimpleDateFormat.
String inputDateInString= "8/15/2017 12:00:00 AM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyy hh:mm:ss");
Date parsedDate = dateFormat.parse("inputDateInString");
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
System.out.println("Timestamp "+ timestamp.getTime());
In case anyone having problem with Samsung GT-I9060 I followed this answer on SO:
If you are on windows, many times it will not recognize the device fully and because of driver issues, the device won't show up.
- go to settings
- control panel
- hardware and sound
- device manager
And look for any devices showing an error. Many androids will show as an unknown USB device. Select that device and try to update the drivers for it.
I uninstalled the device, unplug the device and plug it again. This time Windows properly installed the driver. What a bummer.
Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.
You can also use $inject
to add a dependency:
var MyController = function($scope, $http) {
// ...
}
MyController.$inject = ['$scope', '$http'];
That should be possible using Socket.IO-client: https://github.com/LearnBoost/socket.io-client
You can just CAST your CLOB value into a VARCHAR value and make your querie like a
Can this code be simplified in one if test instead two?
nil
and ''
are different values. If you need to test that s
is neither, IMO you should just compare against both, because it makes your intent the most clear.
That and a few alternatives, with their generated bytecode:
if not foo or foo == '' then end
GETGLOBAL 0 -1 ; foo
TEST 0 0 0
JMP 3 ; to 7
GETGLOBAL 0 -1 ; foo
EQ 0 0 -2 ; - ""
JMP 0 ; to 7
if foo == nil or foo == '' then end
GETGLOBAL 0 -1 ; foo
EQ 1 0 -2 ; - nil
JMP 3 ; to 7
GETGLOBAL 0 -1 ; foo
EQ 0 0 -3 ; - ""
JMP 0 ; to 7
if (foo or '') == '' then end
GETGLOBAL 0 -1 ; foo
TEST 0 0 1
JMP 1 ; to 5
LOADK 0 -2 ; ""
EQ 0 0 -2 ; - ""
JMP 0 ; to 7
The second is fastest in Lua 5.1 and 5.2 (on my machine anyway), but difference is tiny. I'd go with the first for clarity's sake.
Warning: the following is not very nice but it does the job.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
unsigned int id;
char *name;
char *msg;
} error;
#define _printerr(e, s, ...) fprintf(stderr, "\033[1m\033[37m" "%s:%d: " "\033[1m\033[31m" e ":" "\033[1m\033[37m" " ‘%s_error’ " "\033[0m" s "\n", __FILE__, __LINE__, (*__err)->name, ##__VA_ARGS__)
#define printerr(s, ...) _printerr("error", s, ##__VA_ARGS__)
#define printuncaughterr() _printerr("uncaught error", "%s", (*__err)->msg)
#define _errordef(n, _id) \
error* new_##n##_error_msg(char* msg) { \
error* self = malloc(sizeof(error)); \
self->id = _id; \
self->name = #n; \
self->msg = msg; \
return self; \
} \
error* new_##n##_error() { return new_##n##_error_msg(""); }
#define errordef(n) _errordef(n, __COUNTER__ +1)
#define try(try_block, err, err_name, catch_block) { \
error * err_name = NULL; \
error ** __err = & err_name; \
void __try_fn() try_block \
__try_fn(); \
void __catch_fn() { \
if (err_name == NULL) return; \
unsigned int __##err_name##_id = new_##err##_error()->id; \
if (__##err_name##_id != 0 && __##err_name##_id != err_name->id) \
printuncaughterr(); \
else if (__##err_name##_id != 0 || __##err_name##_id != err_name->id) \
catch_block \
} \
__catch_fn(); \
}
#define throw(e) { *__err = e; return; }
_errordef(any, 0)
Usage:
errordef(my_err1)
errordef(my_err2)
try ({
printf("Helloo\n");
throw(new_my_err1_error_msg("hiiiii!"));
printf("This will not be printed!\n");
}, /*catch*/ any, e, {
printf("My lovely error: %s %s\n", e->name, e->msg);
})
printf("\n");
try ({
printf("Helloo\n");
throw(new_my_err2_error_msg("my msg!"));
printf("This will not be printed!\n");
}, /*catch*/ my_err2, e, {
printerr("%s", e->msg);
})
printf("\n");
try ({
printf("Helloo\n");
throw(new_my_err1_error());
printf("This will not be printed!\n");
}, /*catch*/ my_err2, e, {
printf("Catch %s if you can!\n", e->name);
})
Output:
Helloo
My lovely error: my_err1 hiiiii!
Helloo
/home/naheel/Desktop/aa.c:28: error: ‘my_err2_error’ my msg!
Helloo
/home/naheel/Desktop/aa.c:38: uncaught error: ‘my_err1_error’
Keep on mind that this is using nested functions and __COUNTER__
. You'll be on the safe side if you're using gcc.
If you want to draw a horizontal line in the axes, you might also try ax.hlines()
method. You need to specify y
position and xmin
and xmax
in the data coordinate (i.e, your actual data range in the x-axis). A sample code snippet is:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1, 21, 200)
y = np.exp(-x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.hlines(y=0.2, xmin=4, xmax=20, linewidth=2, color='r')
plt.show()
The snippet above will plot a horizontal line in the axes at y=0.2
. The horizontal line starts at x=4
and ends at x=20
. The generated image is:
What is the difference between null and undefined??
A property when it has no definition, is undefined. null is an object. Its type is object. null is a special value meaning "no value. undefined is not an object, it's type is undefined.
You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". You can even compare a variable that is undefined to null or vice versa, and the condition will be true:
undefined == null
null == undefined
Refer to JavaScript Difference between null and undefined for more detail.
and with your new edit yes
if (object == null) does mean the same if(!object)
when testing if object is false, they both only meet the condition when testing if false, but not when true
Check here: Javascript gotcha
Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.
while (sc.hasNext())
{
s1 = sc.next();
System.out.println(s1);
System.out.print("Enter your sentence: ");
}
As per the documentation, you need to specify true
as the second argument if you want an associative array instead of an object from json_decode
. This would be the code:
$result = json_decode($jsondata, true);
If you want integer
keys instead of whatever the property names are:
$result = array_values(json_decode($jsondata, true));
However, with your current decode you just access it as an object:
print_r($obj->Result);
The internals of the GUI system call that method, and they pass in the Graphics
parameter as a graphics context onto which you can draw.
look at the example
window.history.replaceState({
foo: 'bar'
}, 'Nice URL Title', '/nice_url');
window.onpopstate = function (e) {
if (typeof e.state == "object" && e.state.foo == "bar") {
alert("Blah blah blah");
}
};
window.history.go(-1);
and search location.hash
;
// in foo.h
class Foo {
static const unsigned char* Msg;
};
// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;
Delete
operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirementsInsert
for arrays is basically Set
as mentioned in the beginningI copied the current files in a different folder, then get rid of all unpushed changes by:
git reset --hard @{u}
Then copy things back. Commit, Push.
Another oh-so-easy mistake, which was the source of the problem for me: I’d written my own shouldComponentUpdate
method, which didn’t check the new state change I’d added.