This works for me and is quite simple:
Import these:
import java.awt.datatransfer.StringSelection;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
And then put this snippet of code wherever you'd like to alter the clipboard:
String myString = "This text will be copied into clipboard";
StringSelection stringSelection = new StringSelection(myString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
You probably want ANSI color codes. Most *nix terminals support them.
=IF(CR<=10, "RED", if(CR<50, "YELLOW", if(CR<101, "GREEN")))
CR = ColRow (Cell)
This is an example. In this example when value in Cell is less then or equal to 10 then RED word will appear on that cell. In the same manner other if conditions are true if first if is false.
$str='This is a Text \n and so on Text text.';
print preg_replace("/[[:blank:]]+/"," ",$str);
I'm not sure how deep it really is, but:
MyArray.ToList<TSource>().GetRange(beginningIndex, endIndex).ToArray()
It's a bit of overhead, but it might cut out an unnecessary method.
If you want to use hex codes, you should add -e
option to enable interpretation of backslash escapes by echo (but the result is the same as with echo
CtrlRCtrlB). And as wallyk said, you probably want to add -n
to prevent the output of a newline:
echo -en '\x12\x02' > /dev/ttyS0
Also make sure that /dev/ttyS0
is the port you want.
import pytest
class Test:
@pytest.fixture()
def setUp(self):
print("setup")
yield "resource"
print("teardown")
def test_that_depends_on_resource(self, setUp):
print("testing {}".format(setUp))
In order to run:
pytest nam_of_the_module.py -v
Try:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo "record1,record2,record3\n";
die;
etc
Edit: Here's a snippet of code I use to optionally encode CSV fields:
function maybeEncodeCSVField($string) {
if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
$string = '"' . str_replace('"', '""', $string) . '"';
}
return $string;
}
I've got this problem after including same classes twice
step-1. here I'm deploying pos.war First go to tomcat webapps folder and paste it
step-2. go to tomcat->bin folder start tomcat by clicking startup.bat
step-3. go to browser write localhost:port/project name eg. localhost:8080/pos (here my tomcat run on port 8080)
Done....
.move-wrap {
display: table;
table-layout: fixed; // prevent some responsive bugs
width: 100%; // set a width if u like
/* TODO: js-fallback IE7 if u like ms */
}
.move-down {
display: table-footer-group;
}
.move-up {
display: table-header-group;
}
You need to return a view which has a friendly error message to the user
catch (Exception ex)
{
// to do :log error
return View("Error");
}
You should not be showing the internal details of your exception(like exception stacktrace etc) to the user. You should be logging the relevant information to your error log so that you can go through it and fix the issue.
If your request is an ajax request, You may return a JSON response with a proper status flag which client can evaluate and do further actions
[HttpPost]
public ActionResult Create(CustomerVM model)
{
try
{
//save customer
return Json(new { status="success",message="customer created"});
}
catch(Exception ex)
{
//to do: log error
return Json(new { status="error",message="error creating customer"});
}
}
If you want to show the error in the form user submitted, You may use ModelState.AddModelError
method along with the Html helper methods like Html.ValidationSummary
etc to show the error to the user in the form he submitted.
You can set it as a no title bar theme in the activity's xml in the AndroidManifest
<activity
android:name=".AnActivity"
android:label="@string/a_string"
android:theme="@android:style/Theme.NoTitleBar">
</activity>
I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.
Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.
Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.
Simplified example (with counter):
With Me.lstbox
.ColumnCount = 2
.ColumnWidths = "60;60"
.AddItem
.List(i, 0) = Company_ID
.List(i, 1) = Company_name
i = i + 1
end with
Make sure to start the counter with 0, not 1 to fill up a listbox.
A full version of the solution will be wrapping the method upvotes inside onClick, passing e and use native e.preventDefault();
upvotes = (e, arg1, arg2, arg3 ) => {
e.preventDefault();
//do something...
}
render(){
return (<a type="simpleQuery" onClick={ e => this.upvotes(e, arg1, arg2, arg3) }>
upvote
</a>);
{
This has happened to me also, after undating to IOS11 on my iPhone. When I try to connect to the corporate network it bring up the corporate cert and says it isn't trusted. I press the 'trust' button and the connection fails and the cert does not appear in the trusted certs list.
It doesn't appear that you are actually using the email that you retrieve from the database, but an older copy that you get as a parameter. Whatever is being used for version control on the row has changed between when the previous version was retrieved and when you are doing the update.
You probably want your code to look more like:
@Transactional
public void test(String id, String subject) {
Email email = getEmailById(id);
email.setSubject(subject);
updateEmail(email);
}
Another problem could be that the Android Project Build Target is not set.
You can use the "export" solution just like what other guys have suggested. I'd like to provide you with another solution for permanent convenience: you can use any path as GOPATH when running Go commands.
Firstly, you need to download a small tool named gost
: https://github.com/byte16/gost/releases . If you use ubuntu, you can download the linux version(https://github.com/byte16/gost/releases/download/v0.1.0/gost_linux_amd64.tar.gz).
Then you need to run the commands below to unpack it :
$ cd /path/to/your/download/directory
$ tar -xvf gost_linux_amd64.tar.gz
You would get an executable gost
. You can move it to /usr/local/bin
for convenient use:
$ sudo mv gost /usr/local/bin
Run the command below to add the path you want to use as GOPATH into the pathspace gost
maintains. It is required to give the path a name which you would use later.
$ gost add foo /home/foobar/bar # 'foo' is the name and '/home/foobar/bar' is the path
Run any Go command you want in the format:
gost goCommand [-p {pathName}] -- [goFlags...] [goArgs...]
For example, you want to run go get github.com/go-sql-driver/mysql
with /home/foobar/bar
as the GOPATH, just do it as below:
$ gost get -p foo -- github.com/go-sql-driver/mysql # 'foo' is the name you give to the path above.
It would help you to set the GOPATH and run the command. But remember that you have added the path into gost
's pathspace. If you are under any level of subdirectories of /home/foobar/bar
, you can even just run the command below which would do the same thing for short :
$ gost get -- github.com/go-sql-driver/mysql
gost
is a Simple Tool of Go which can help you to manage GOPATHs and run Go commands. For more details about how to use it to run other Go commands, you can just run gost help goCmdName
. For example you want to know more about install
, just type words below in:
$ gost help install
You can also find more details in the README of the project: https://github.com/byte16/gost/blob/master/README.md
The important thing is that the icon you want to be displayed as the application icon ( in the title bar and in the task bar ) must be the FIRST icon in the resource script file
The file is in the res folder and is named (applicationName).rc
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
(icon ID ) ICON "res\\filename.ico"
Component: Subscribe to all routing events instead of creating an action in the template and scroll on NavigationEnd b/c otherwise you'll fire this off on bad navs or blocked routes, etc... This is a sure fire way to know that if a route successfully is navigated to, then sooth scroll. Otherwise, do nothing.
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
router$: Subscription;
constructor(private router: Router) {}
ngOnInit() {
this.router$ = this.router.events.subscribe(next => this.onRouteUpdated(next));
}
ngOnDestroy() {
if (this.router$ != null) {
this.router$.unsubscribe();
}
}
private onRouteUpdated(event: any): void {
if (event instanceof NavigationEnd) {
this.smoothScrollTop();
}
}
private smoothScrollTop(): void {
const scrollToTop = window.setInterval(() => {
const pos: number = window.pageYOffset;
if (pos > 0) {
window.scrollTo(0, pos - 20); // how far to scroll on each step
} else {
window.clearInterval(scrollToTop);
}
}, 16);
}
}
HTML
<router-outlet></router-outlet>
In Python 3, all strings are unicode. Usually, if you encode an unicode object to a string, you use .encode('TEXT_ENCODING')
, since hex
is not a text encoding, you should use codecs.encode()
to handle arbitrary codecs. For example:
>>>> "hello".encode('hex')
LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
>>>> import codecs
>>>> codecs.encode(b"hello", 'hex')
b'68656c6c6f'
Again, since "hello" is unicode, you need to indicate it as a byte string before encoding to hexadecimal. This may be more inline with what your original approach of using the encode
method.
The differences between binascii.hexlify
and codecs.encode
are as follow:
binascii.hexlify
Hexadecimal representation of binary data.
The return value is a bytes object.
Type: builtin_function_or_method
codecs.encode
encode(obj, [encoding[,errors]]) -> object
Encodes obj using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a ValueError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle ValueErrors.
Type: builtin_function_or_method
The code below is the simplest solution:
Bitmap bt = new Bitmap("imageFilePath");
for (int y = 0; y < bt.Height; y++)
{
for (int x = 0; x < bt.Width; x++)
{
Color c = bt.GetPixel(x, y);
int r = c.R;
int g = c.G;
int b = c.B;
int avg = (r + g + b) / 3;
bt.SetPixel(x, y, Color.FromArgb(avg,avg,avg));
}
}
bt.Save("d:\\out.bmp");
Datetime is a datatype.
Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.
For more information:
http://www.sqlteam.com/article/timestamps-vs-datetime-data-types
1. install moment
npm install moment --save
2. test this code in your typescript file
import moment = require('moment');
console.log(moment().format('LLLL'));
Do you know View.getViewTreeObserver().addOnGlobalLayoutListener()
By this you can calculate the sizes.
I achieve your UI effect by GridView:
GridView g;
g.setNumColumns(2);
g.setStretchMode(GridView.STRETCH_SPACING_UNIFORM);
Set args = Wscript.Arguments
For Each arg In args
Wscript.Echo arg
Next
From a command prompt, run the script like this:
CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"
Will give results like this:
1
2
A
B
Arg with spaces
The problem is that in IE (which is what I presume you're testing in), the <iframe>
element has a document
property that refers to the document containing the iframe, and this is getting used before the contentDocument
or contentWindow.document
properties. What you need is:
function GetDoc(x) {
return x.contentDocument || x.contentWindow.document;
}
Also, document.all
is not available in all browsers and is non-standard. Use document.getElementById()
instead.
With Git 2.23 (August 2019), that would be, using git switch -f
:
git switch -f master
That avoids the confusion with git checkout
(which deals with files or branches).
And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules
is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.
I find it useful to understand the underlying tools. These are cl.exe (compiler) and link.exe (linker). You need to tell the compiler the signatures of the functions you want to call in the dynamic library (by including the library's header) and you need to tell the linker what the library is called and how to call it (by including the "implib" or import library).
This is roughly the same process gcc uses for linking to dynamic libraries on *nix, only the library object file differs.
Knowing the underlying tools means you can more quickly find the appropriate settings in the IDE and allows you to check that the commandlines generated are correct.
Say A.exe depends B.dll. You need to include B's header in A.cpp (#include "B.h"
) then compile and link with B.lib:
cl A.cpp /c /EHsc
link A.obj B.lib
The first line generates A.obj, the second generates A.exe. The /c
flag tells cl not to link and /EHsc
specifies what kind of C++ exception handling the binary should use (there's no default, so you have to specify something).
If you don't specify /c
cl will call link
for you. You can use the /link
flag to specify additional arguments to link
and do it all at once if you like:
cl A.cpp /EHsc /link B.lib
If B.lib is not on the INCLUDE
path you can give a relative or absolute path to it or add its parent directory to your include path with the /I
flag.
If you're calling from cygwin (as I do) replace the forward slashes with dashes.
If you write #pragma comment(lib, "B.lib")
in A.cpp you're just telling the compiler to leave a comment in A.obj telling the linker to link to B.lib. It's equivalent to specifying B.lib on the link commandline.
def x(a):
print(a)
return a
def y(a):
return a
y(x(1))
I had this problem.
I solved it with this solution, by giving CREATOR OWNER full rights to the Windows Temp folder. For some reason, that user had no rights at all assigned. Maybe because some time ago I ran Combofix on my computer.
Building on @Kristian's answer, I had a desire to display a fixed number of decimal places. That can be accomplished with other arguments in the QString::number(...)
function. For instance, I wanted 3 decimal places:
double value = 34.0495834;
QString strValue = QString::number(value, 'f', 3);
// strValue == "34.050"
The 'f'
specifies decimal format notation (more info here, you can also specify scientific notation) and the 3
specifies the precision (number of decimal places). Probably already linked in other answers, but more info about the QString::number
function can be found here in the QString
documentation
This is an old question, but since I was looking for full page load but for Spookyjs (that uses casperjs and phantomjs) and didn't find my solution, I made my own script for that, with the same approach as the user deemstone . What this approach does is, for a given quantity of time, if the page did not receive or started any request it will end the execution.
On casper.js file (if you installed it globally, the path would be something like /usr/local/lib/node_modules/casperjs/modules/casper.js) add the following lines:
At the top of the file with all the global vars:
var waitResponseInterval = 500
var reqResInterval = null
var reqResFinished = false
var resetTimeout = function() {}
Then inside function "createPage(casper)" just after "var page = require('webpage').create();" add the following code:
resetTimeout = function() {
if(reqResInterval)
clearTimeout(reqResInterval)
reqResInterval = setTimeout(function(){
reqResFinished = true
page.onLoadFinished("success")
},waitResponseInterval)
}
resetTimeout()
Then inside "page.onResourceReceived = function onResourceReceived(resource) {" on the first line add:
resetTimeout()
Do the same for "page.onResourceRequested = function onResourceRequested(requestData, request) {"
Finally, on "page.onLoadFinished = function onLoadFinished(status) {" on the first line add:
if(!reqResFinished)
{
return
}
reqResFinished = false
And that's it, hope this one helps someone in trouble like I was. This solution is for casperjs but works directly for Spooky.
Good luck !
We do it differently. IMHO we do it in an easier way: in master
we are working on the next major version.
Each larger feature gets its own branch (derived from master) and will be rebased (+ force pushed) on top of master regularly by the developer. Rebasing only works fine if a single developer works on this feature. If the feature is finished, it will be freshly rebased onto master and then the master fast-forwarded to the latest feature commit.
To avoid the rebasing/forced push one also can merge master changes regularly to the feature branch and if it's finished merge the feature branch into master (normal merge or squash merge). But IMHO this makes the feature branch less clear and makes it much more difficult to reorder/cleanup the commits.
If a new release is coming, we create a side-branch out of master, e.g. release-5
where only bugs get fixed.
Quick answer : Add proxy configuration with parameter for both install/update
gem install --http-proxy http://host:port/ package_name
gem update --http-proxy http://host:port/ package_name
is there a possibility that casting a double created via
Math.round()
will still result in a truncated down number
No, round()
will always round your double to the correct value, and then, it will be cast to an long
which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.
Here are the docs from Math.round(double)
:
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)
As of C++11, the standard C++ library provides the function std::to_string(arg)
with various supported types for arg
.
Unsorted vector:
if (std::find(v.begin(), v.end(),value)!=v.end())
...
Sorted vector:
if (std::binary_search(v.begin(), v.end(), value)
...
P.S. may need to include <algorithm>
header
Try this instead
SELECT MAX(shoppername), COUNT(*) AS cnt
FROM dbo.sales
GROUP BY CHECKSUM(*)
HAVING COUNT(*) > 1
Read about the CHECKSUM function first, as there can be duplicates.
Another way created by eGerman that uses PE numbers of compiled executables (does not rely on registry records or environment variables):
@echo off &setlocal
call :getPETarget "%SystemRoot%\explorer.exe"
if "%=ExitCode%" EQU "00008664" (
echo x64
) else (
if "%=ExitCode%" EQU "0000014C" (
echo x32
) else (
echo undefined
)
)
goto :eof
:getPETarget FilePath
:: ~~~~~~~~~~~~~~~~~~~~~~
:: Errorlevel
:: 0 Success
:: 1 File Not Found
:: 2 Wrong Magic Number
:: 3 Out Of Scope
:: 4 No PE File
:: ~~~~~~~~~~~~~~~~~~~~~~
:: =ExitCode
:: CPU identifier
setlocal DisableDelayedExpansion
set "File=%~1"
set Cmp="%temp%\%random%.%random%.1KB"
set Dmp="%temp%\%random%.%random%.dmp"
REM write 1024 times 'A' into a temporary file
if exist "%File%" (
>%Cmp% (
for /l %%i in (1 1 32) do <nul set /p "=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
)
setlocal EnableDelayedExpansion
) else (endlocal &cmd /c exit 0 &exit /b 1)
REM generate a HEX dump of the executable file (first 1024 Bytes)
set "X=1"
>!Dmp! (
for /f "skip=1 tokens=1,2 delims=: " %%i in ('fc /b "!File!" !Cmp!^|findstr /vbi "FC:"') do (
set /a "Y=0x%%i"
for /l %%k in (!X! 1 !Y!) do echo 41
set /a "X=Y+2"
echo %%j
)
)
del !Cmp!
REM read certain values out of the HEX dump
set "err="
<!Dmp! (
set /p "A="
set /p "B="
REM magic number has to be "MZ"
if "!A!!B!" neq "4D5A" (set "err=2") else (
REM skip next 58 bytes
for /l %%i in (3 1 60) do set /p "="
REM bytes 61-64 contain the offset to the PE header in little endian order
set /p "C="
set /p "D="
set /p "E="
set /p "F="
REM check if the beginning of the PE header is part of the HEX dump
if 0x!F!!E!!D!!C! lss 1 (set "err=3") else (
if 0x!F!!E!!D!!C! gtr 1018 (set "err=3") else (
REM skip the offset to the PE header
for /l %%i in (65 1 0x!F!!E!!D!!C!) do set /p "="
REM next 4 bytes have to contain the signature of the PE header
set /p "G="
set /p "H="
set /p "I="
set /p "J="
REM next 2 bytes contain the CPU identifier in little endian order
set /p "K="
set /p "L="
)
)
)
)
del !Dmp!
if defined err (endlocal &endlocal &cmd /c exit 0 &exit /b %err%)
REM was the signature ("PE\0\0") of the PE header found
if "%G%%H%%I%%J%"=="50450000" (
REM calculate the decimal value of the CPU identifier
set /a "CPUID=0x%L%%K%"
) else (endlocal &endlocal &cmd /c exit 0 &exit /b 4)
endlocal &endlocal &cmd /c exit %CPUID% &exit /b 0
By splitting the number into an array and reversing we can easily check the last 2 digits of the number using array[0]
and array[1]
.
If a number is in the teens array[1] = 1
it requires "th".
function getDaySuffix(num)
{
var array = ("" + num).split("").reverse(); // E.g. 123 = array("3","2","1")
if (array[1] != "1") { // Number is in the teens
switch (array[0]) {
case "1": return "st";
case "2": return "nd";
case "3": return "rd";
}
}
return "th";
}
It's even simpler than that. Just did this (on Windows, but it should work on other OS):
Git just sees you added a directory and renamed a bunch of files. No biggie.
To access "Host Manager" you have to configure "admin-gui" user inside the tomcat-users.xml
Just add the below lines[change username & pwd] :
<role rolename="admin-gui"/>
<user username="admin" password="password" roles="admin-gui"/>
Restart tomcat 7 server and you are done.
If you just want to disable App Transport Policy for local dev servers then the following solutions work well. It's useful when you're unable, or it's impractical, to set up HTTPS (e.g. when using the Google App Engine dev server).
As others have said though, ATP should definitely not be turned off for production apps.
Copy your Plist file and NSAllowsArbitraryLoads. Use this Plist for debugging.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Alternatively, you can use a single plist file and exclude specific servers. However, it doesn't look like you can exclude IP 4 addresses so you might need to use the server name instead (found in System Preferences -> Sharing, or configured in your local DNS).
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>server.local</key>
<dict/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
All you have to do is have a height of 100vh on your main container/wrapper, and then set height 100% or 50% for child elements.. depending on what you're trying to achieve. I tried to copy your mock up in a basic sense.
In case you want to center stuff within, look into flexbox. I put in an example for you.
You can view it on full screen, and resize the browser and see how it works. The layout stays the same.
.left {_x000D_
background: grey; _x000D_
}_x000D_
_x000D_
.right {_x000D_
background: black; _x000D_
}_x000D_
_x000D_
.main-wrapper {_x000D_
height: 100vh; _x000D_
}_x000D_
_x000D_
.section {_x000D_
height: 100%; _x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
.half {_x000D_
background: #f9f9f9;_x000D_
height: 50%; _x000D_
width: 100%;_x000D_
margin: 15px 0;_x000D_
}_x000D_
_x000D_
h4 {_x000D_
color: white; _x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<div class="main-wrapper">_x000D_
<div class="section left col-xs-3">_x000D_
<div class="half"><h4>Top left</h4></div>_x000D_
<div class="half"><h4>Bottom left</h4></div>_x000D_
</div>_x000D_
<div class="section right col-xs-9">_x000D_
<h4>Extra step: center stuff here</h4>_x000D_
</div>_x000D_
</div>
_x000D_
Warning by @Geoff: see my note below, only one of the suggestions in this answer works (though on both columns).
I would use sed
:
sed 's/, /,/' input.txt
This will remove on leading space after the ,
.
Output:
Name,Order
Trim,working
cat,cat1
More general might be the following, it will remove possibly multiple spaces and/or tabs after the ,
:
sed 's/,[ \t]\?/,/g' input.txt
It will also work with more than two columns because of the global modifier /g
@Floris asked in discussion for a solution that removes trailing and and ending whitespaces in each colum (even the first and last) while not removing white spaces in the middle of a column:
sed 's/[ \t]\?,[ \t]\?/,/g; s/^[ \t]\+//g; s/[ \t]\+$//g' input.txt
*EDIT by @Geoff, I've appended the input file name to this one, and now it only removes all leading & trailing spaces (though from both columns). The other suggestions within this answer don't work. But try: " Multiple spaces , and 2 spaces before here " *
IMO sed
is the optimal tool for this job. However, here comes a solution with awk
because you've asked for that:
awk -F', ' '{printf "%s,%s\n", $1, $2}' input.txt
Another simple solution that comes in mind to remove all whitespaces is tr -d
:
cat input.txt | tr -d ' '
No actual difference unless you get the type string. There when you use reflection or GetType() you get {Name = "Boolean" FullName = "System.Boolean"} for both.
The main difference is that
substr() allows you to specify the maximum length to return
substring() allows you to specify the indices and the second argument is NOT inclusive
There are some additional subtleties between substr() and substring() such as the handling of equal arguments and negative arguments. Also note substring() and slice() are similar but not always the same.
//*** length vs indices:
"string".substring(2,4); // "ri" (start, end) indices / second value is NOT inclusive
"string".substr(2,4); // "ring" (start, length) length is the maximum length to return
"string".slice(2,4); // "ri" (start, end) indices / second value is NOT inclusive
//*** watch out for substring swap:
"string".substring(3,2); // "r" (swaps the larger and the smaller number)
"string".substr(3,2); // "in"
"string".slice(3,2); // "" (just returns "")
//*** negative second argument:
"string".substring(2,-4); // "st" (converts negative numbers to 0, then swaps first and second position)
"string".substr(2,-4); // ""
"string".slice(2,-4); // ""
//*** negative first argument:
"string".substring(-3); // "string"
"string".substr(-3); // "ing" (read from end of string)
"string".slice(-3); // "ing"
This question is ancient but..
Right after the opening body tag..
<!--[if gte IE 8]>
<div id="IE8Body">
<![endif]-->
Right before the closing body tag..
<!--[if gte IE 8]>
</div>
<![endif]-->
CSS..
#IE8Body #nav li ul {}
You could do this for all IE browsers using conditional statements, OR target ALL browsers by encapsulating all content in a div with browser name + version server-side
Resize to fit the container, get scale factor, scale down percentage control
$(function () {
let ParentHeight = 200;
let ParentWidth = 300;
$("#Parent").width(ParentWidth).height(ParentHeight);
$("#ParentHeight").html(ParentHeight);
$("#ParentWidth").html(ParentWidth);
var RatioOfParent = ParentHeight / ParentWidth;
$("#ParentAspectRatio").html(RatioOfParent);
let ChildHeight = 2000;
let ChildWidth = 4000;
var RatioOfChild = ChildHeight / ChildWidth;
$("#ChildAspectRatio").html(RatioOfChild);
let ScaleHeight = ParentHeight / ChildHeight;
let ScaleWidth = ParentWidth / ChildWidth;
let Scale = Math.min(ScaleHeight, ScaleWidth);
$("#ScaleFactor").html(Scale);
// old scale
//ChildHeight = ChildHeight * Scale;
//ChildWidth = ChildWidth * Scale;
// reduce scale by 10%, you can change the percentage
let ScaleDownPercentage = 10;
let CalculatedScaleValue = Scale * (ScaleDownPercentage / 100);
$("#CalculatedScaleValue").html(CalculatedScaleValue);
// new scale
let NewScale = (Scale - CalculatedScaleValue);
ChildHeight = ChildHeight * NewScale;
ChildWidth = ChildWidth * NewScale;
$("#Child").width(ChildWidth).height(ChildHeight);
$("#ChildHeight").html(ChildHeight);
$("#ChildWidth").html(ChildWidth);
});
_x000D_
#Parent {
background-color: grey;
}
#Child {
background-color: red;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Parent">
<div id="Child"></div>
</div>
<table>
<tr>
<td>Parent Aspect Ratio</td>
<td id="ParentAspectRatio"></td>
</tr>
<tr>
<td>Child Aspect Ratio</td>
<td id="ChildAspectRatio"></td>
</tr>
<tr>
<td>Scale Factor</td>
<td id="ScaleFactor"></td>
</tr>
<tr>
<td>Calculated Scale Value</td>
<td id="CalculatedScaleValue"></td>
</tr>
<tr>
<td>Parent Height</td>
<td id="ParentHeight"></td>
</tr>
<tr>
<td>Parent Width</td>
<td id="ParentWidth"></td>
</tr>
<tr>
<td>Child Height</td>
<td id="ChildHeight"></td>
</tr>
<tr>
<td>Child Width</td>
<td id="ChildWidth"></td>
</tr>
</table>
_x000D_
You can use convert
from hablar
to change a column of the data frame quickly.
library(tidyverse)
library(hablar)
x <- tibble(var = c(1.34, 4.45, 6.98))
x %>%
convert(int(var))
gives you:
# A tibble: 3 x 1
var
<int>
1 1
2 4
3 6
This might due to merge conflict same as mine, try to change local.properties for me it was wrong location for android sdk as it was override from other machine ndk.dir=/Users/???/Library/Android/sdk/ndk-bundle sdk.dir=/Users/???/Library/Android/sdk
then rebuild
Try negation operator !
before $(this)
:
if (!$(this).parent().next().is('ul')){
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
Try this
$('.yourchkboxes').change(function(){
$('.yourbutton').toggle($('.yourchkboxes:checked').length > 0);
});
So it will check for at least one checkbox is checked or not.
Here is a way to easily escape & char in oracle DB
set escape '\\'
and within query write like
'ERRORS &\\\ PERFORMANCE';
The following solved my problem of converting string into date
package main
import (
"fmt"
"time"
)
func main() {
value := "Thu, 05/19/11, 10:47PM"
// Writing down the way the standard time would look like formatted our way
layout := "Mon, 01/02/06, 03:04PM"
t, _ := time.Parse(layout, value)
fmt.Println(t)
}
// => "Thu May 19 22:47:00 +0000 2011"
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
I'm going to try this the following way. I've placed the count variable inside the "onfocus" function so as to keep it from becoming a global variable. The idea is to create a counter for each image in a tumblr blog.
$(document).ready(function() {
$("#image1").onfocus(function() {
var count;
if (count == undefined || count == "" || count == 0) {
var count = 0;
}
count++;
$("#counter1").html("Image Views: " + count);
}
});
Then, outside the script tags and in the desired place in the body I'll add:
<div id="counter1"></div>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/META-INF/PersistenceContext.xml
</param-value>
</context-param>
I have initialized my PersistenceContext.xml
within <context-param>
because all my servlets will be interacting with database in MVC framework.
Howerver,
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:ApplicationContext.xml
</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.organisation.project.rest</param-value>
</init-param>
</servlet>
in the aforementioned code, I am configuring jersey and the ApplicationContext.xml
only to rest layer. For the same I am using </init-param>
To get every part of the URL except for the query:
var url = (location.origin).concat(location.pathname).concat(location.hash);
Note that this includes the hash as well, if there is one (I'm aware there's no hash in your example URL, but I included that aspect for completeness). To eliminate the hash, simply exclude .concat(location.hash)
.
It's better practice to use concat
to join Javascript strings together (rather than +
): in some situations it avoids problems such as type confusion.
The JailCoder references above point to a site that does not exist any more. Looks like you should use http://oneiros.altervista.org/jailcoder/ or https://www.facebook.com/jailcoder
The whereami library by Gregory Pakosz implements this for a variety of platforms, using the APIs mentioned in mark4o's post. This is most interesting if you "just" need a solution that works for a portable project and are not interested in the peculiarities of the various platforms.
At the time of writing, supported platforms are:
The library consists of whereami.c
and whereami.h
and is licensed under MIT and WTFPL2. Drop the files into your project, include the header and use it:
#include "whereami.h"
int main() {
int length = wai_getExecutablePath(NULL, 0, NULL);
char* path = (char*)malloc(length + 1);
wai_getExecutablePath(path, length, &dirname_length);
path[length] = '\0';
printf("My path: %s", path);
free(path);
return 0;
}
You can use ng-repeat
and pick data only if data matches what you are looking for using ng-show
for example:
<div ng-repeat="data in res.results" ng-show="data.id==1">
{{data.name}}
</div>
I'm not sure if I am correct, but from the request header that you post:
Request headers
Accept: Application/json
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8
it seems like you didn't config your request body to JSON type.
The amount of capacity which is to be exhausted for the HashMap to increase its capacity ?
Load factor is by default 0.75 of the initial capacity (16) therefore 25% of the buckets will be free before there is an increase in the capacity & this makes many new buckets with new hashcodes pointing to them to exist just after the increase in the number of buckets.
If you set the loading factor to say 1.0 then something very interesting might happen.
Say you are adding an object x to your hashmap whose hashCode is 888 & in your hashmap the bucket representing the hashcode is free , so the object x gets added to the bucket, but now again say if you are adding another object y whose hashCode is also 888 then your object y will get added for sure BUT at the end of the bucket (because the buckets are nothing but linkedList implementation storing key,value & next) now this has a performance impact ! Since your object y is no longer present in the head of the bucket if you perform a lookup the time taken is not going to be O(1) this time it depends on how many items are there in the same bucket. This is called hash collision by the way & this even happens when your loading factor is less than 1.
Lower load factor = more free buckets = less chances of collision = high performance = high space requirement.
Correct me if i am wrong somewhere.
Stolen from the post on this issue at CodingHorror:
Unfortunately, you and everyone else pretty much got it wrong. While I agree with you that redundancy is not a good thing, the better way to solve this issue would have been to do something like the following:
MyObject m = new();
Or if you are passing parameters:
Person p = new("FirstName", "LastName);
Where in the creation of a new object, the compiler infers the type from the left-hand side, and not the right. This has other advantages over "var", in that it could be used in field declarations as well (there are also some other areas that it could be useful as well, but I won't get into it here).
In the end, it just wasn't intended to reduce redundancy. Don't get me wrong, "var" is VERY important in C# for anonymous types/projections, but the use here is just WAY off (and I've been saying this for a long, long time) as you obfuscate the type that is being used. Having to type it twice is too often, but declaring it zero times is too few.
Nicholas Paldino .NET/C# MVP on June 20, 2008 08:00 AM
I guess if your main concern is to have to type less -- then there isn't any argument that's going to sway you from using it.
If you are only going to ever be the person who looks at your code, then who cares? Otherwise, in a case like this:
var people = Managers.People
it's fine, but in a case like this:
var fc = Factory.Run();
it short circuits any immediate type deductions my brain could begin forming from the 'English' of the code.
Otherwise, just use your best judgment and programming 'courtesy' towards others who might have to work on your project.
Thank you for the code, it's just what I was looking for. I have also added the following code to Vimal's code, to implement the case of a CustomCellBackgroundViewPositionSingle cell. (All four corners are rounded.)
else if (position == CustomCellBackgroundViewPositionSingle)
{
CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ;
CGFloat miny = CGRectGetMinY(rect) , midy = CGRectGetMidY(rect) , maxy = CGRectGetMaxY(rect) ;
minx = minx + 1;
miny = miny + 1;
maxx = maxx - 1;
maxy = maxy - 1;
CGContextMoveToPoint(c, minx, midy);
CGContextAddArcToPoint(c, minx, miny, midx, miny, ROUND_SIZE);
CGContextAddArcToPoint(c, maxx, miny, maxx, midy, ROUND_SIZE);
CGContextAddArcToPoint(c, maxx, maxy, midx, maxy, ROUND_SIZE);
CGContextAddArcToPoint(c, minx, maxy, minx, midy, ROUND_SIZE);
// Close the path
CGContextClosePath(c);
// Fill & stroke the path
CGContextDrawPath(c, kCGPathFillStroke);
return;
}
Here are the steps for send email from localhost by wamp server with Sendmail.
C:\wamp\sendmail\sendmail.ini
smtp_server=smtp.gmail.com smtp_port=465 [email protected] auth_password=your_password
"C:\wamp\bin\php\php5.5.12\php.ini"
and
"C:\wamp\bin\apache\apache2.4.9\bin\php.ini"
set sendmail_path ** sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"
It will surely be worked.
You can't sort a std::map
this way, because a the entries in the map are sorted by the key. If you want to sort by value, you need to create a new std::map
with swapped key and value.
map<long, double> testMap;
map<double, long> testMap2;
// Insert values from testMap to testMap2
// The values in testMap2 are sorted by the double value
Remember that the double keys need to be unique in testMap2
or use std::multimap
.
In Pyspark, to run local spark application using Pycharm use below lines
os.environ['HADOOP_HOME'] = "C:\\winutils"
print os.environ['HADOOP_HOME']
the simplest way I can think to explain this is by using some pseudo code
so
list of 1, 2 ,3
for each item in list
templist.Add(item)
for each item2 in list
if item2 is Not item
templist.add(item)
for each item3 in list
if item2 is Not item
templist.add(item)
end if
Next
end if
Next
permanentListofPermutaitons,add(templist)
tempList.Clear()
Next
Now obviously this is not the most flexible way to do this, and doing it recursively would be a lot more functional by my tired sunday night brain doesn't want to think about that at this moment. If no ones put up a recursive version by the morning I'll do one.
Here's an extension method. Not sure where I found it.
public static class StringExtensions
{
public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)
{
int startIndex = 0;
while (true)
{
startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);
if (startIndex == -1)
break;
originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);
startIndex += newValue.Length;
}
return originalString;
}
}
If you are using Url.Action
inside JavaScript then you can
var personId="someId";
$.ajax({
type: 'POST',
url: '@Url.Action("CreatePerson", "Person")',
dataType: 'html',
data: ({
//insert your parameters to pass to controller
id: personId
}),
success: function() {
alert("Successfully posted!");
}
});
The definitions are detailed at the Maven site's page Introduction to the Build Lifecycle, but I have tried to summarize:
Maven defines 4 items of a build process:
Lifecycle
Three built-in lifecycles (aka build lifecycles): default
, clean
, site
. (Lifecycle Reference)
Phase
Each lifecycle is made up of phases, e.g. for the default
lifecycle: compile
, test
, package
, install
, etc.
Plugin
An artifact that provides one or more goals.
Based on packaging type (jar
, war
, etc.) plugins' goals are bound to phases by default. (Built-in Lifecycle Bindings)
Goal
The task (action) that is executed. A plugin can have one or more goals.
One or more goals need to be specified when configuring a plugin in a POM. Additionally, in case a plugin does not have a default phase defined, the specified goal(s) can be bound to a phase.
Maven can be invoked with:
clean
, package
)<plugin-prefix>:<goal>
(e.g. dependency:copy-dependencies
)<plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>
(e.g. org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile
)with one or more combinations of any or all, e.g.:
mvn clean dependency:copy-dependencies package
I'm a bit newer to Angular but what I found useful to do (and pretty simple) is I made a global script that I load onto my page before the local script with global variables that I need to access on all pages anyway. In that script, I created an object called "globalFunctions" and added the functions that I need to access globally as properties. e.g. globalFunctions.foo = myFunc();
. Then, in each local script, I wrote $scope.globalFunctions = globalFunctions;
and I instantly have access to any function I added to the globalFunctions object in the global script.
This is a bit of a workaround and I'm not sure it helps you but it definitely helped me as I had many functions and it was a pain adding all of them to each page.
Use an html button and javascript? in javascript, window.location
is used to change the url location of the current window, while window.open
will open a new one
<input type="button" onclick="window.open('newPage.aspx', 'newPage');" />
Edit: Ah, just found this: If the ID of your form tag is form1
, set this attribute in your asp button
OnClientClick="form1.target ='_blank';"
HTML:
<button onclick="render()">Render</button>
<canvas id="myCanvas" height="100" width="100" style="object-fit:contain;"></canvas>
CSS:
canvas {
width: 400px;
height: 200px;
border: 1px solid red;
display: block;
}
Javascript:
const myCanvas = document.getElementById("myCanvas");
const originalHeight = myCanvas.height;
const originalWidth = myCanvas.width;
render();
function render() {
let dimensions = getObjectFitSize(
true,
myCanvas.clientWidth,
myCanvas.clientHeight,
myCanvas.width,
myCanvas.height
);
myCanvas.width = dimensions.width;
myCanvas.height = dimensions.height;
let ctx = myCanvas.getContext("2d");
let ratio = Math.min(
myCanvas.clientWidth / originalWidth,
myCanvas.clientHeight / originalHeight
);
ctx.scale(ratio, ratio); //adjust this!
ctx.beginPath();
ctx.arc(50, 50, 50, 0, 2 * Math.PI);
ctx.stroke();
}
// adapted from: https://www.npmjs.com/package/intrinsic-scale
function getObjectFitSize(
contains /* true = contain, false = cover */,
containerWidth,
containerHeight,
width,
height
) {
var doRatio = width / height;
var cRatio = containerWidth / containerHeight;
var targetWidth = 0;
var targetHeight = 0;
var test = contains ? doRatio > cRatio : doRatio < cRatio;
if (test) {
targetWidth = containerWidth;
targetHeight = targetWidth / doRatio;
} else {
targetHeight = containerHeight;
targetWidth = targetHeight * doRatio;
}
return {
width: targetWidth,
height: targetHeight,
x: (containerWidth - targetWidth) / 2,
y: (containerHeight - targetHeight) / 2
};
}
Basically, canvas.height/width sets the size of the bitmap you are rendering to. The CSS height/width then scales the bitmap to fit the layout space (often warping it as it scales it). The context can then modify it's scale to draw, using vector operations, at different sizes.
Prerequisites: 1. If you have multiple Modules 2. And you are using a component (suppose DemoComponent) from a different module (suppose AModule), in a different module (suppose BModule)
Then Your AModule should be
@NgModule({
declarations: [DemoComponent],
imports: [
CommonModule
],
exports: [AModule]
})
export class AModule{ }
and your BModule should be
@NgModule({
declarations: [],
imports: [
CommonModule, AModule
],
exports: [],
})
export class BModule { }
Your code has no problem. It does print the way you want. Alternatively, you can do this:
printf("%04x",a);
Another option would be to use the package ggplot2
.
ggplot(mydata, aes(x = V3)) + geom_histogram() + scale_x_log10()
This solution works using Bootstrap v2, however in TBS3 the class INLINE. I haven't figured out what is the equivalent class (if there is one) in TBS3.
This gentleman had a pretty good article of the differences between v2 and v3.
http://mattduchek.com/differences-between-bootstrap-v2-3-and-v3-0/
EDIT - use CSS to target the li
elements to solve your problem as below
{ display: inline-block; }
In my situation I was targeting the UL, instead of the LI
nav ul li { display: inline-block; }
Try this query:
select top 1 TotalRows = count(*) over ()
from yourTable
group by column1, column2
Use this
Intent i1=new Intent(getApplicationContext(),StartUp_Page.class);
i1.setAction(Intent.ACTION_MAIN);
i1.addCategory(Intent.CATEGORY_HOME);
i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i1);
finish();
It depends on the kind of data you are using. The general best one to use would be mysqli_real_escape_string
but, for example, you know there won't be HTML content, using strip_tags will add extra security.
You can also remove characters you know shouldn't be allowed.
Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:
big = 1e5;
tic;
x = rand(big,1);
toc
x = zeros(big,1);
tic;
for ii = 1:big
x(ii) = rand;
end
toc
x = [];
tic;
for ii = 1:big
x(end+1) = rand;
end;
toc
x = [];
tic;
for ii = 1:big
x = [x rand];
end;
toc
Elapsed time is 0.004611 seconds.
Elapsed time is 0.016448 seconds.
Elapsed time is 0.034107 seconds.
Elapsed time is 12.341434 seconds.
I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get
Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.
So I guess the speed advantage only applies to more recent versions of Matlab
Another thing that helps improve the accuracy of what I do isn't really a management studio tip but one using t-sql itself.
Whenever I write an update or delete statement for the first time, I incorporate a select into it so that I can see what records will be affected.
Examples:
select t1.field1,t2.field2
--update t
--set field1 = t2.field2
from mytable t1
join myothertable t2 on t1.idfield =t2.idfield
where t2.field1 >10
select t1.*
--delete t1
from mytable t1
join myothertable t2 on t1.idfield =t2.idfield
where t2.field1 = 'test'
(note I used select * here just for illustration, I would normally only select the few fields I need to see that the query is correct. Sometimes I might need to see fields from the other tables inthe join as well as the records I plan to delete to make sure the join worked the way I thought it would)
When you run this code, you run the select first to ensure it is correct, then comment the select line(s) out and uncomment the delete or update parts. By doing it this way, you don't accidentally run the delete or update before you have checked it. Also you avoid the problem of forgetting to comment out the select causing the update to update all records in the database table that can occur if you use this syntax and uncomment the select to run it:
select t1.field1,t2.field2
update t
set field1 = t2.field2
--select t1.field1,t2.field2
from mytable t1
join myothertable t2 on t1.idfield =t2.idfield
where t2.field1 >10
As you can see from the example above, if you uncomment the select and forget to re-comment it out, oops you just updated the whole table and then ran a select when you thought to just run the update. Someone just did that in my office this week making it so only one person of all out clients could log into the client websites. So avoid doing this.
Flex is the better way. Just try..
display: flex;
Yes, you can hide only the rows that you want to hide. This can be helpful if you want to show rows only when some condition is satisfied in the rows that are currently being shown. The following worked for me.
<table>
<tr><th>Sample Table</th></tr>
<tr id="row1">
<td><input id="data1" type="text" name="data1" /></td>
</tr>
<tr id="row2" style="display: none;">
<td><input id="data2" type="text" name="data2" /></td>
</tr>
<tr id="row3" style="display: none;">
<td><input id="data3" type="text" name="data3" /></td>
</tr>
</table>
In CSS, do the following:
#row2{
display: none;
}
#row3{
display: none;
}
In JQuery, you might have something like the following to show the desired rows.
$(document).ready(function(){
if($("#row1").val() === "sometext"){ //your desired condition
$("#row2").show();
}
if($("#row2").val() !== ""){ //your desired condition
$("#row3").show();
}
});
An array "decays" into a pointer to its first element, so scanf("%s", string)
is equivalent to scanf("%s", &string[0])
. On the other hand, scanf("%s", &string)
passes a pointer-to-char[256]
, but it points to the same place.
Then scanf
, when processing the tail of its argument list, will try to pull out a char *
. That's the Right Thing when you've passed in string
or &string[0]
, but when you've passed in &string
you're depending on something that the language standard doesn't guarantee, namely that the pointers &string
and &string[0]
-- pointers to objects of different types and sizes that start at the same place -- are represented the same way.
I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)
Padding aligns structure members to "natural" address boundaries - say, int
members would have offsets, which are mod(4) == 0
on 32-bit platform. Padding is on by default. It inserts the following "gaps" into your first structure:
struct mystruct_A {
char a;
char gap_0[3]; /* inserted by compiler: for alignment of b */
int b;
char c;
char gap_1[3]; /* -"-: for alignment of the whole struct in an array */
} x;
Packing, on the other hand prevents compiler from doing padding - this has to be explicitly requested - under GCC it's __attribute__((__packed__))
, so the following:
struct __attribute__((__packed__)) mystruct_A {
char a;
int b;
char c;
};
would produce structure of size 6
on a 32-bit architecture.
A note though - unaligned memory access is slower on architectures that allow it (like x86 and amd64), and is explicitly prohibited on strict alignment architectures like SPARC.
A strong reference (which you will use in most cases) means that you want to "own" the object you are referencing with this property/variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you point to it with a strong reference. Only once you set the property to nil
will the object get destroyed (unless one or more other objects also hold a strong reference to it).
In contrast, with a weak reference you signify that you don't want to have control over the object's lifetime. The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil
. The most frequent use cases of weak references in iOS are:
delegate properties, which are often referenced weakly to avoid retain cycles, and
subviews/controls of a view controller's main view because those views are already strongly held by the main view.
atomic vs. nonatomic refers to the thread safety of the getter and setter methods that the compiler synthesizes for the property. atomic (the default) tells the compiler to make the accessor methods thread-safe (by adding a lock before an ivar is accessed) and nonatomic does the opposite. The advantage of nonatomic is slightly higher performance. On iOS, Apple uses nonatomic for almost all their properties so the general advice is for you to do the same.
There is number of methods to allocate an array of intrinsic type and all of these method are correct, though which one to choose, depends...
Manual initialisation of all elements in loop
int* p = new int[10];
for (int i = 0; i < 10; i++)
p[i] = 0;
Using std::memset
function from <cstring>
int* p = new int[10];
std::memset(p, 0, sizeof *p * 10);
Using std::fill_n
algorithm from <algorithm>
int* p = new int[10];
std::fill_n(p, 10, 0);
Using std::vector
container
std::vector<int> v(10); // elements zero'ed
If C++11 is available, using initializer list features
int a[] = { 1, 2, 3 }; // 3-element static size array
vector<int> v = { 1, 2, 3 }; // 3-element array but vector is resizeable in runtime
You create a file .xml in drawable with name drop_shadow.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--<item android:state_pressed="true">
<layer-list>
<item android:left="4dp" android:top="4dp">
<shape>
<solid android:color="#35000000" />
<corners android:radius="2dp"/>
</shape>
</item>
...
</layer-list>
</item>-->
<item>
<layer-list>
<!-- SHADOW LAYER -->
<!--<item android:top="4dp" android:left="4dp">
<shape>
<solid android:color="#35000000" />
<corners android:radius="2dp" />
</shape>
</item>-->
<!-- SHADOW LAYER -->
<item>
<shape>
<solid android:color="#35000000" />
<corners android:radius="2dp" />
</shape>
</item>
<!-- CONTENT LAYER -->
<item android:bottom="3dp" android:left="1dp" android:right="3dp" android:top="1dp">
<shape>
<solid android:color="#ffffff" />
<corners android:radius="1dp" />
</shape>
</item>
</layer-list>
</item>
</selector>
Then:
<LinearLayout
...
android:background="@drawable/drop_shadow"/>
you can use this to get the data of the last 30 days based on a column.
WHERE DATEDIFF(dateColumn,CURRENT_TIMESTAMP) BETWEEN 0 AND 30
from inside vim, use one of the following
open a new window below the current one:
:new filename.ext
open a new window beside the current one:
:vert new filename.ext
A bitwise or operator can be used to truncate floating point figures and it works for positives as well as negatives:
function float2int (value) {
return value | 0;
}
Results
float2int(3.1) == 3
float2int(-3.1) == -3
float2int(3.9) == 3
float2int(-3.9) == -3
I've created a JSPerf test that compares performance between:
Math.floor(val)
val | 0
bitwise OR~~val
bitwise NOTparseInt(val)
that only works with positive numbers. In this case you're safe to use bitwise operations well as Math.floor
function.
But if you need your code to work with positives as well as negatives, then a bitwise operation is the fastest (OR being the preferred one). This other JSPerf test compares the same where it's pretty obvious that because of the additional sign checking Math is now the slowest of the four.
As stated in comments, BITWISE operators operate on signed 32bit integers, therefore large numbers will be converted, example:
1234567890 | 0 => 1234567890
12345678901 | 0 => -539222987
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;
But your table has:
CREATE TABLE `katalog` (
`Sprache` int(11) NOT NULL,
It cant set the column Sprache to NULL because it is defined as NOT NULL.
Try adding this module, pretty simple, just launches Access, opens the database, sets the "Compact on Close" option to "True", then quits.
Syntax to auto-compact:
acCompactRepair "C:\Folder\Database.accdb", True
To return to default*:
acCompactRepair "C:\Folder\Database.accdb", False
*not necessary, but if your back end database is >1GB this can be rather annoying when you go into it directly and it takes 2 minutes to quit!
EDIT: added option to recurse through all folders, I run this nightly to keep databases down to a minimum.
'accCompactRepair
'v2.02 2013-11-28 17:25
'===========================================================================
' HELP CONTACT
'===========================================================================
' Code is provided without warranty and can be stolen and amended as required.
' Tom Parish
' [email protected]
' http://baldywrittencod.blogspot.com/2013/10/vba-modules-access-compact-repair.html
' DGF Help Contact: see BPMHelpContact module
'=========================================================================
'includes code from
'http://www.ammara.com/access_image_faq/recursive_folder_search.html
'tweaked slightly for improved error handling
' v2.02 bugfix preventing Compact when bAutoCompact set to False
' bugfix with "OLE waiting for another application" msgbox
' added "MB" to start & end sizes of message box at end
' v2.01 added size reduction to message box
' v2.00 added recurse
' v1.00 original version
Option Explicit
Function accSweepForDatabases(ByVal strFolder As String, Optional ByVal bIncludeSubfolders As Boolean = True _
, Optional bAutoCompact As Boolean = False) As String
'v2.02 2013-11-28 17:25
'sweeps path for .accdb and .mdb files, compacts and repairs all that it finds
'NB: leaves AutoCompact on Close as False unless specified, then leaves as True
'syntax:
' accSweepForDatabases "path", [False], [True]
'code for ActiveX CommandButton on sheet module named "admin" with two named ranges "vPath" and "vRecurse":
' accSweepForDatabases admin.Range("vPath"), admin.Range("vRecurse") [, admin.Range("vLeaveAutoCompact")]
Application.DisplayAlerts = False
Dim colFiles As New Collection, vFile As Variant, i As Integer, j As Integer, sFails As String, t As Single
Dim SizeBefore As Long, SizeAfter As Long
t = Timer
RecursiveDir colFiles, strFolder, "*.accdb", True 'comment this out if you only have Access 2003 installed
RecursiveDir colFiles, strFolder, "*.mdb", True
For Each vFile In colFiles
'Debug.Print vFile
SizeBefore = SizeBefore + (FileLen(vFile) / 1048576)
On Error GoTo CompactFailed
If InStr(vFile, "Geographical Configuration.accdb") > 0 Then MsgBox "yes"
acCompactRepair vFile, bAutoCompact
i = i + 1 'counts successes
GoTo NextCompact
CompactFailed:
On Error GoTo 0
j = j + 1 'counts failures
sFails = sFails & vFile & vbLf 'records failure
NextCompact:
On Error GoTo 0
SizeAfter = SizeAfter + (FileLen(vFile) / 1048576)
Next vFile
Application.DisplayAlerts = True
'display message box, mark end of process
accSweepForDatabases = i & " databases compacted successfully, taking " & CInt(Timer - t) & " seconds, and reducing storage overheads by " & Int(SizeBefore - SizeAfter) & "MB" & vbLf & vbLf & "Size Before: " & Int(SizeBefore) & "MB" & vbLf & "Size After: " & Int(SizeAfter) & "MB"
If j > 0 Then accSweepForDatabases = accSweepForDatabases & vbLf & j & " failures:" & vbLf & vbLf & sFails
MsgBox accSweepForDatabases, vbInformation, "accSweepForDatabases"
End Function
Function acCompactRepair(ByVal pthfn As String, Optional doEnable As Boolean = True) As Boolean
'v2.02 2013-11-28 16:22
'if doEnable = True will compact and repair pthfn
'if doEnable = False will then disable auto compact on pthfn
On Error GoTo CompactFailed
Dim A As Object
Set A = CreateObject("Access.Application")
With A
.OpenCurrentDatabase pthfn
.SetOption "Auto compact", True
.CloseCurrentDatabase
If doEnable = False Then
.OpenCurrentDatabase pthfn
.SetOption "Auto compact", doEnable
End If
.Quit
End With
Set A = Nothing
acCompactRepair = True
Exit Function
CompactFailed:
End Function
'source: http://www.ammara.com/access_image_faq/recursive_folder_search.html
'tweaked slightly for error handling
Private Function RecursiveDir(colFiles As Collection, _
strFolder As String, _
strFileSpec As String, _
bIncludeSubfolders As Boolean)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
'Add files in strFolder matching strFileSpec to colFiles
strFolder = TrailingSlash(strFolder)
On Error Resume Next
strTemp = ""
strTemp = Dir(strFolder & strFileSpec)
On Error GoTo 0
Do While strTemp <> vbNullString
colFiles.Add strFolder & strTemp
strTemp = Dir
Loop
If bIncludeSubfolders Then
'Fill colFolders with list of subdirectories of strFolder
On Error Resume Next
strTemp = ""
strTemp = Dir(strFolder, vbDirectory)
On Error GoTo 0
Do While strTemp <> vbNullString
If (strTemp <> ".") And (strTemp <> "..") Then
If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
colFolders.Add strTemp
End If
End If
strTemp = Dir
Loop
'Call RecursiveDir for each subfolder in colFolders
For Each vFolderName In colFolders
Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
Next vFolderName
End If
End Function
Private Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
If Right(strFolder, 1) = "\" Then
TrailingSlash = strFolder
Else
TrailingSlash = strFolder & "\"
End If
End If
End Function
adb disable-verity
adb reboot
adb root
adb remount
This works for me, and is the simplest solution.
I really like explanation by Jeremy west.... another approach which is really easy for understanding is given here http://courses.washington.edu/css343/zander/NotesProbs/heapcomplexity
since, buildheap depends using depends on heapify and shiftdown approach is used which depends upon sum of the heights of all nodes. So, to find the sum of height of nodes which is given by S = summation from i = 0 to i = h of (2^i*(h-i)), where h = logn is height of the tree solving s, we get s = 2^(h+1) - 1 - (h+1) since, n = 2^(h+1) - 1 s = n - h - 1 = n- logn - 1 s = O(n), and so complexity of buildheap is O(n).
I just updated matplotlib to 1.1.0 on my system and it now allows me to save to jpg with savefig
.
To upgrade to matplotlib 1.1.0 with pip
, use this command:
pip install -U 'http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz/download'
EDIT (to respond to comment):
pylab
is simply an aggregation of the matplotlib.pyplot and numpy namespaces (as well as a few others) jinto a single namespace.
On my system, pylab
is just this:
from matplotlib.pylab import *
import matplotlib.pylab
__doc__ = matplotlib.pylab.__doc__
You can see that pylab
is just another namespace in your matplotlib installation. Therefore, it doesn't matter whether or not you import it with pylab
or with matplotlib.pyplot
.
If you are still running into problem, then I'm guessing the macosx backend doesn't support saving plots to jpg. You could try using a different backend. See here for more information.
All answers are awesome and explained everything very well
but I just want to point out different way for passing args to main method
in visual studio
like this image
and happy knowing secrets
Try passing width=200
as additional paramater when creating the Label.
This should work in creating label with specified width.
If you want to change it later, you can use:
label.config(width=200)
As you want to change the size of font itself you can try:
label.config(font=("Courier", 44))
You would use it as the first line of a subclass constructor to call the constructor of its parent class.
For example:
public class TheSuper{
public TheSuper(){
eatCake();
}
}
public class TheSub extends TheSuper{
public TheSub(){
super();
eatMoreCake();
}
}
Constructing an instance of TheSub
would call both eatCake()
and eatMoreCake()
to_csv
with date_format
parameterAvoid, where possible, converting your datetime64[ns]
series to an object
dtype series of datetime.date
objects. The latter, often constructed using pd.Series.dt.date
, is stored as an array of pointers and is inefficient relative to a pure NumPy-based series.
Since your concern is format when writing to CSV, just use the date_format
parameter of to_csv
. For example:
df.to_csv(filename, date_format='%Y-%m-%d')
See Python's strftime
directives for formatting conventions.
A simple call back program. Hope it answers your question.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "../../common_typedef.h"
typedef void (*call_back) (S32, S32);
void test_call_back(S32 a, S32 b)
{
printf("In call back function, a:%d \t b:%d \n", a, b);
}
void call_callback_func(call_back back)
{
S32 a = 5;
S32 b = 7;
back(a, b);
}
S32 main(S32 argc, S8 *argv[])
{
S32 ret = SUCCESS;
call_back back;
back = test_call_back;
call_callback_func(back);
return ret;
}
Make sure you are in the project directory before running bundle install
. For example, after running rails new myproject
, you will want to cd myproject
before running bundle install
.
CAST(CONVERT(CHAR(8),GETUTCDATE(),114) AS DATETIME)
IN SQL Server 2008+
CAST(GETUTCDATE() AS TIME)
Indexing a list is done using double bracket, i.e. hypo_list[[1]]
(e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table
does not return a table but a dataframe (see value section in ?read.table
). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.
Note: In R, the index for the first entry is a 1
(not 0
like in some other languages).
Dataframes
l <- list(anscombe, iris) # put dfs in list
l[[1]] # returns anscombe dataframe
anscombe[1:2, 2] # access first two rows and second column of dataset
[1] 10 8
l[[1]][1:2, 2] # the same but selecting the dataframe from the list first
[1] 10 8
Table objects
tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2) # put tables in a list
tbl1[1:2] # access first two elements of table 1
Now with the list
l[[1]] # access first table from the list
1 2 3 4 5
9 11 12 9 9
l[[1]][1:2] # access first two elements in first table
1 2
9 11
Open up a command terminal (CTRL+ALT+T) and try running this command:
anaconda-navigator
When I installed Anaconda, and read the website docs, they said that they tend to not add a file or menu path to run the navigator because there are so many different versions of different systems, instead they give the above terminal command to start the navigator GUI and advise on setting up a shortcut to do this process manually - if that works for you it shouldn't be too much trouble to do it this way - I do it like this personally
$('body').append($('<div/>', {
id: 'holdy'
}));
the answer for those with shared hosting. Best to use this little script which I just used to import a 300mb DB file to my server. The script is called Big Dump.
provides a script to import large DB's on resource-limited servers
Found this on a different forum
If you're wondering why that leading zero is important, it's because permissions are set as an octal integer, and Python automagically treats any integer with a leading zero as octal. So os.chmod("file", 484) (in decimal) would give the same result.
What you are doing is passing 664
which in octal is 1230
In your case you would need
os.chmod("/tmp/test_file", 436)
[Update] Note, for Python 3 you have prefix with 0o (zero oh). E.G, 0o666
It require to include Content-Type:application/json
in web api request header section when not mention any content then by default it is Content-Type:text/plain
passes to request.
Best way to test api on postman tool.
strace sqlplus -L scott/tiger@orcl
helps to find .tnsnames.ora
file on /home/oracle
to find the file it takes instead of $ORACLE_HOME/network/admin/tnsnames.ora
file. Thanks for the posting.
In my case, it's because a trigger is triggered before a insert cause, (actually it means to split a big table in several tables using timestamp), and then return null. So I met this problem when I used springboot jpa save() function.
In addition to change the trigger to SET NOCOUNT ON;
Mr. TA mentioned above, the solution can also be using native query.
insert into table values(nextval('table_id_seq'), value1)
JsSimpleDateFormat is a library that can format the date object and parse the formatted string back to Date object. It uses the Java format (SimpleDateFormat class). The name of months and days can be localized.
Example:
var sdf = new JsSimpleDateFormat("EEEE, MMMM dd, yyyy");
var formattedString = sdf.format(new Date());
var dateObject = sdf.parse("Monday, June 29, 2009");
I just want to echo sam9046's modest comment as an alternative and potentially much easier solution that worked in my case: uninstall and install homebrew again from scratch. No sudo commands required.
You can also browse/modify the uninstall script from that link above if you need to ensure it won't affect your previously installed packages. In my case this was just my home machine so I just started over.
For cases where you also wish to have the option of setting 'b' to None:
def p(self, **kwargs):
b = kwargs.get('b', self.a)
print b
you can use it directly with $scope instance
$scope.init=function()
{
console.log("entered");
data={};
/*do whatever you want such as initialising scope variable,
using $http instance etcc..*/
}
//simple call init function on controller
$scope.init();
enum MyEnum
{ A_ENUM_VALUE=0,
B_ENUM_VALUE,
C_ENUM_VALUE
};
int main()
{
printf("My enum Value : %d\n", (int)C_ENUM_VALUE);
return 0;
}
You have just to cast enum to int !
Output : My enum Value : 2
Here's a fairly simple way to achieve it by enclosing both the magnifying glass icon and the input field inside a div with relative positioning.
Absolute positioning is applied to the icon, which takes it out of the normal document layout flow. The icon is then positioned inside the input. Left padding is applied to the input so that the user's input appears to the right of the icon.
Note that this example places the magnifying glass icon on the left instead of the right. This is recommended when using <input type="search">
as Chrome adds an X button in the right side of the searchbox. If we placed the icon there it would overlay the X button and look fugly.
Here is the needed Bootstrap markup.
<div class="position-relative">
<i class="fa fa-search position-absolute"></i>
<input class="form-control" type="search">
</div>
...and a couple CSS classes for the things which I couldn't do with Bootstrap classes:
i {
font-size: 1rem;
color: #333;
top: .75rem;
left: .75rem
}
input {
padding-left: 2.5rem;
}
You may have to fiddle with the values for top, left, and padding-left.
I created it a long time ago, related question
String.Format = function (b) {
var a = arguments;
return b.replace(/(\{\{\d\}\}|\{\d\})/g, function (b) {
if (b.substring(0, 2) == "{{") return b;
var c = parseInt(b.match(/\d/)[0]);
return a[c + 1]
})
};
All the updates for new version of xcode will be available in appstore if you have installed the version from appstore. If you just paste the downloaded version appstore will show install not update. Hence keep the stable version downloaded from appstore in your applications folder.
To try new beta releases i usually put it in separate drive and unzip and install it there. This will avoid confusion while working on stable version.
To avoid confusion you can keep only the stable version in your dock and open the beta version from spotlight(Command + Space). This will place beta temporarily on dock. But it will make sure you don't accidentally edit your client project in beta version.
Most Important:- Working on same project on two different xcode might create some unwanted results. Like there was a bug in interface builder that got introduced in certain version of xcode. Which broke the constraints. It got fixed again in the next one.
Keep track of release notes to know exactly what are additional features and what are known issues.
nohup some_command &> nohup2.out &
and voila.
Older syntax for Bash version < 4:
nohup some_command > nohup2.out 2>&1 &
Bash is a Command Line Interface that was created over twenty-seven years ago by Brian Fox as a free software replacement for the Bourne Shell. A shell is a specific kind of Command Line Interface. Bash is "open source" which means that anyone can read the code and suggest changes. Since its beginning, it has been supported by a large community of engineers who have worked to make it an incredible tool. Bash is the default shell for Linux and Mac. For these reasons, Bash is the most used and widely distributed shell.
Windows has a different Command Line Interface, called Command Prompt. While this has many of the same features as Bash, Bash is much more popular. Because of the strength of the open source community and the tools they provide, mastering Bash is a better investment than mastering Command Prompt.
To use Bash on a Windows computer, we need to download and install a program called Git Bash. Git Bash (Is the Bash for windows) allows us to easily access Bash as well as another tool called Git, inside the Windows environment.
Maybe these steps are not quite correct, but I do like this:
stop docker compose: $ docker-compose down
remove the container: $ docker system prune -a
start docker compose: $ docker-compose up -d
Here is a really simple way. You said you want to cat, which implies you want to view the entire file. But you also need the filename printed.
Try this
head -n99999999 *
or head -n99999999 file1.txt file2.txt file3.txt
Hope that helps
Your problem is in passing the result of moment.duration() back into moment() before formatting it; this results in moment() interpreting it as a time relative to the Unix epoch.
It doesn't give you exactly the format you're looking for, but
moment.duration(now.diff(then)).humanize()
would give you a useful format like "40 minutes". If you're really keen on that specific formatting, you'll have to build a new string yourself. A cheap way would be
[diff.asHours(), diff.minutes(), diff.seconds()].join(':')
where var diff = moment.duration(now.diff(then))
. This doesn't give you the zero-padding on single digit values. For that, you might want to consider something like underscore.string - although it seems like a long way to go just for a few extra zeroes. :)
Try the following decorators:
@app.route('/email/',methods=['POST', 'OPTIONS']) #Added 'Options'
@crossdomain(origin='*') #Added
def hello_world():
name=request.form['name']
email=request.form['email']
phone=request.form['phone']
description=request.form['description']
mandrill.send_email(
from_email=email,
from_name=name,
to=[{'email': app.config['QOLD_SUPPORT_EMAIL']}],
text="Phone="+phone+"\n\n"+description
)
return '200 OK'
if __name__ == '__main__':
app.run()
This decorator would be created as follows:
from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
You can also check out this package Flask-CORS
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
First of all, if you are trying to encode apostophes for querystrings, they need to be URLEncoded, not escaped with a leading backslash. For that use URLEncoder.encode(String, String)
(BTW: the second argument should always be "UTF-8"
). Secondly, if you want to replace all instances of apostophe with backslash apostrophe, you must escape the backslash in your string expression with a leading backslash. Like this:
"This is' it".replace("'", "\\'");
I see now that you are probably trying to dynamically build a SQL statement. Do not do it this way. Your code will be susceptible to SQL injection attacks. Instead use a PreparedStatement
.
With <button>
, you can use img tags, etc. where text is
<button type='submit'> text -- can be img etc. </button>
with <input>
type, you are limited to text
often this is due to missing permissions. The windows account the local IIS Application Pool is running with may not have the permission to write to the applications directory. You could create a directory somewhere, give everyone permission to write in it and point your log4net config to that directory. If then a log file is created there, you can modify the permissions for your desired log directory so that the app pool can write to it.
Another reason could be an uninitialized log4net. In a winforms app, you usually configure log4net upon application start. In a web app, you can do this either dynamically (in your logging component, check if you can create a specific Ilog logger using its name, if not -> call configure()) or again upon application start in global.asax.cs.
For posterity, your question was how to send an http request to https://stackoverflow.com/questions
. The real answer is: you cannot with telnet, cause this is an https-only reachable url.
So, you might want to use openssl
instead of telnet
, like this for instance
$ openssl s_client -connect stackoverflow.com:443
...
---
GET /questions HTTP/1.1
Host: stackoverflow.com
This will give you the https response.
Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions).
This is a basic skeleton for a simple service:
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
pass
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
Your code would go in the main()
method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the SvcStop
method
I think that your mistake is in that your route should be product
instead of /product
.
So more something like
children: [
{
path: '',
component: AboutHomeComponent
},
{
path: 'product',
component: AboutItemComponent
}
]
Since you've already looked into strtok
just continue down the same path and split your string using space (' '
) as a delimiter, then use something as realloc
to increase the size of the array containing the elements to be passed to execvp
.
See the below example, but keep in mind that strtok
will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy
or similar function.
char str[]= "ls -l";
char ** res = NULL;
char * p = strtok (str, " ");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p;
p = strtok (NULL, " ");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
res[0] = ls
res[1] = -l
res[2] = (null)
Macros in Notepad++ are just a bunch of encoded operations: you start recording, operate on the buffer, perhaps activating menus, stop recording then play the macro.
After investigation, I found out they are saved in the file shortcuts.xml in the Macros section. For example, I have there:
<Macro name="Trim Trailing and save" Ctrl="no" Alt="yes" Shift="yes" Key="83">
<Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
<Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
<Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
<Action type="0" message="2327" wParam="0" lParam="0" sParam="" />
<Action type="0" message="2327" wParam="0" lParam="0" sParam="" />
<Action type="2" message="0" wParam="42024" lParam="0" sParam="" />
<Action type="2" message="0" wParam="41006" lParam="0" sParam="" />
</Macro>
I haven't looked at the source, but from the look, I would say we have messages sent to Scintilla (the editing component, perhaps type 0 and 1), and to Notepad++ itself (probably activating menu items).
I don't think it will record actions in dialogs (like search/replace).
Looking at Scintilla.iface file, we can see that 2170 is the code of ReplaceSel (ie. insert string is nothing is selected), 2327 is Tab command, and Resource Hacker (just have it handy...) shows that 42024 is "Trim Trailing Space" menu item and 41006 is "Save".
I guess action type 0 is for Scintilla commands with numerical params, type 1 is for commands with string parameter, 2 is for Notepad++ commands.
Problem: Scintilla doesn't have a "Replace all" command: it is the task of the client to do the iteration, with or without confirmation, etc.
Another problem: it seems type 1 action is limited to 1 char (I edited manually, when exiting N++ it was truncated).
I tried some tricks, but I fear such task is beyond the macro capabilities.
Maybe that's where SciTE with its Lua scripting ability (or Programmer's Notepad which seems to be scriptable with Python) has an edge... :-)
[EDIT] Looks like I got the above macro from this thread or a similar place... :-) I guess the first lines are unnecessary (side effect or recording) but they were good examples of macro code anyway.
In cases where the name attribute is different it is easiest to control the radio group via JQuery. When an option is selected use JQuery to un-select the other options.
Because when you access a static field, you should do so on the class (or in this case the enum). As in
MyUnits.MILLISECONDS;
Not on an instance as in
m.MILLISECONDS;
Edit To address the question of why: In Java, when you declare something as static
, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.
50% of C++ programmers like to set their pointers to null after a delete:
template<typename T>
void moronic_delete(T*& p)
{
delete p;
p = nullptr;
}
Without the reference, you would only be changing a local copy of the pointer, not affecting the caller.
You can make an object animator. For example, I have a targetView and I want to change your background color:
int colorFrom = Color.RED;
int colorTo = Color.GREEN;
int duration = 1000;
ObjectAnimator.ofObject(targetView, "backgroundColor", new ArgbEvaluator(), colorFrom, colorTo)
.setDuration(duration)
.start();
You might want to consider using console.log
with the built-in "arguments" object:
console.log(arguments); // would have shown you [0] null, [1] yourResult
This will always output all of your arguments, no matter how many arguments you have.
use:
$scope.users.length;
Instead of:
$scope.users.lenght;
And next time "spell-check" your code.
In fact, eclipse export will call
java -jar android-sdk-windows\tools\lib\sdklib.jar com.android.sdklib.build.ApkBuilderMain
and then call com.android.sdklib.internal.build.SignedJarBuilder.
function reloadScrollBars() {
document.documentElement.style.overflow = 'auto'; // firefox, chrome
document.body.scroll = "yes"; // ie only
}
function unloadScrollBars() {
document.documentElement.style.overflow = 'hidden'; // firefox, chrome
document.body.scroll = "no"; // ie only
}
Based on .NET 4.5
Sample code below
using System;
enum Importance
{
None,
Low,
Medium,
Critical
}
class Program
{
static void Main()
{
// The input value.
string value = "Medium";
// An unitialized variable.
Importance importance;
// Call Enum.TryParse method.
if (Enum.TryParse(value, out importance))
{
// We now have an enum type.
Console.WriteLine(importance == Importance.Medium);
}
}
}
Reference : http://www.dotnetperls.com/enum-parse
On Centos 5.3 I'm able to do:
mail -s "Subject" [email protected] -- -f [email protected] < body
The double dash stops mail from parsing the -f argument and passes it along to sendmail itself.
This guide is oriented to developers who already have an application in the Play Store. If you are starting with a new app the process it's much easier and you can follow the guidelines of paragraph "New apps" from here
Prerequisites that 99% of developers already have :
Android Studio
JDK 8 and after installation you need to setup an environment variable in your user space to simplify terminal commands. In Windows x64 you need to add this : C:\Program Files\Java\{JDK_VERSION}\bin
to the Path
environment variable. (If you don't know how to do this you can read my guide to add a folder to the Windows 10 Path
environment variable).
Step 0: Open Google Play developer console, then go to Release Management -> App Signing.
Accept the App Signing TOS.
Step 1: Download PEPK Tool clicking the button identical to the image below
Step 2: Open a terminal and type:
java -jar PATH_TO_PEPK --keystore=PATH_TO_KEYSTORE --alias=ALIAS_YOU_USE_TO_SIGN_APK --output=PATH_TO_OUTPUT_FILE --encryptionkey=GOOGLE_ENCRYPTION_KEY
Legend:
C:\Users\YourName\Downloads\pepk.jar
for Windows users.C:\Android\mykeystore
or C:\Android\mykeystore.keystore
etc...C:\Android\private_key.pem
eb10fe8f7c7c9df715022017b00c6471f8ba8170b13049a11e6c09ffe3056a104a3bbe4ac5a955f4ba4fe93fc8cef27558a3eb9d2a529a2092761fb833b656cd48b9de6a
Example:
java -jar "C:\Users\YourName\Downloads\pepk.jar" --keystore="C:\Android\mykeystore" --alias=myalias --output="C:\Android\private_key.pem" --encryptionkey=eb10fe8f7c7c9df715022017b00c6471f8ba8170b13049a11e6c09ffe3056a104a3bbe4ac5a955f4ba4fe93fc8cef27558a3eb9d2a529a2092761fb833b656cd48b9de6a
Press Enter and you will need to provide in order:
If everything has gone OK, you now will have a file in PATH_TO_OUTPUT_FILE folder called private_key.pem
.
Step 3: Upload the private_key.pem file clicking the button identical to the image below
Step 4: Create a new keystore file using Android Studio.
YOU WILL NEED THIS KEYSTORE IN THE FUTURE TO SIGN THE NEXT RELEASES OF YOUR APP, DON'T FORGET THE PASSWORDS
Open one of your Android projects (choose one at random). Go to Build -> Generate Signed APK and press Create new.
Now you should fill the required fields.
Key store path represent the new keystore you will create, choose a folder and a name using the 3 dots icon on the right, i choosed
C:\Android\upload_key.jks
(.jks extension will be added automatically)NOTE: I used
upload
as the new alias name but if you previously used the same keystore with different aliases to sign different apps, you should choose the same aliases name you had previously in the original keystore.
Press OK when finished, and now you will have a new upload_key.jks
keystore. You can close Android Studio now.
Step 5: We need to extract the upload certificate from the newly created upload_key.jks
keystore.
Open a terminal and type:
keytool -export -rfc -keystore UPLOAD_KEYSTORE_PATH -alias UPLOAD_KEYSTORE_ALIAS -file PATH_TO_OUTPUT_FILE
Legend:
C:\Android\upload_key.jks
.upload
.C:\Android\upload_key_public_certificate.pem
.Example:
keytool -export -rfc -keystore "C:\Android\upload_key.jks" -alias upload -file "C:\Android\upload_key_public_certificate.pem"
Press Enter and you will need to provide the keystore password.
Now if everything has gone OK, you will have a file in the folder PATH_TO_OUTPUT_FILE called upload_key_public_certificate.pem
.
Step 6: Upload the upload_key_public_certificate.pem
file clicking the button identical to the image below
Step 7: Click ENROLL button at the end of the App Signing page.
Now every new release APK must be signed with the upload_key.jks
keystore and aliases created in Step 4, prior to be uploaded in the Google Play Developer console.
More Resources:
Q: When i upload the APK signed with the new upload_key keystore, Google Play show an error like : You uploaded an unsigned APK. You need to create a signed APK.
A: Check to sign the APK with both signatures (V1 and V2) while building the release APK. Read here for more details.
The step 4,5,6 are to create upload key which is optional for existing apps
"Upload key (optional for existing apps): A new key you generate during your enrollment in the program. You will use the upload key to sign all future APKs prior to uploading them to the Play Console." https://support.google.com/googleplay/android-developer/answer/7384423
I have written two simple functions that give the same functionality as $stmt->get_result();
, but they don't require the mysqlnd driver.
You simply replace
$result = $stmt->get_result();
with $fields = bindAll($stmt);
and
$row= $stmt->get_result();
with $row = fetchRowAssoc($stmt, $fields);
.
(To get the numbers of returned rows you can use $stmt->num_rows
.)
You just have to place these two functions I have written somewhere in your PHP Script. (for example right at the bottom)
function bindAll($stmt) {
$meta = $stmt->result_metadata();
$fields = array();
$fieldRefs = array();
while ($field = $meta->fetch_field())
{
$fields[$field->name] = "";
$fieldRefs[] = &$fields[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $fieldRefs);
$stmt->store_result();
//var_dump($fields);
return $fields;
}
function fetchRowAssoc($stmt, &$fields) {
if ($stmt->fetch()) {
return $fields;
}
return false;
}
How it works:
My code uses the $stmt->result_metadata();
function to figure out how many and which fields are returned and then automatically binds the fetched results to pre-created references. Works like a charm!
#import "NSDataAdditions.h"
@implementation NSData (NSDataAdditions)
+ (NSData *) base64DataFromString: (NSString *)string {
unsigned long ixtext, lentext;
unsigned char ch, input[4], output[3];
short i, ixinput;
Boolean flignore, flendtext = false;
const char *temporary;
NSMutableData *result;
if (!string)
return [NSData data];
ixtext = 0;
temporary = [string UTF8String];
lentext = [string length];
result = [NSMutableData dataWithCapacity: lentext];
ixinput = 0;
while (true) {
if (ixtext >= lentext)
break;
ch = temporary[ixtext++];
flignore = false;
if ((ch >= 'A') && (ch <= 'Z'))
ch = ch - 'A';
else if ((ch >= 'a') && (ch <= 'z'))
ch = ch - 'a' + 26;
else if ((ch >= '0') && (ch <= '9'))
ch = ch - '0' + 52;
else if (ch == '+')
ch = 62;
else if (ch == '=')
flendtext = true;
else if (ch == '/')
ch = 63;
else
flignore = true;
if (!flignore) {
short ctcharsinput = 3;
Boolean flbreak = false;
if (flendtext) {
if (ixinput == 0)
break;
if ((ixinput == 1) || (ixinput == 2))
ctcharsinput = 1;
else
ctcharsinput = 2;
ixinput = 3;
flbreak = true;
}
input[ixinput++] = ch;
if (ixinput == 4){
ixinput = 0;
output[0] = (input[0] << 2) | ((input[1] & 0x30) >> 4);
output[1] = ((input[1] & 0x0F) << 4) | ((input[2] & 0x3C) >> 2);
output[2] = ((input[2] & 0x03) << 6) | (input[3] & 0x3F);
for (i = 0; i < ctcharsinput; i++)
[result appendBytes: &output[i] length: 1];
}
if (flbreak)
break;
}
}
return result;
}
@end
You need to change the password directly in the database because at mysql the users and their profiles are saved in the database.
So there are several ways. At phpMyAdmin you simple go to user admin, choose root and change the password.
Since v-ref is no longer a directive, but a special attribute, it can also be dynamically defined. This is especially useful in combination with v-for.
For example:
<ul>
<li v-for="(item, key) in items" v-on:click="play(item,$event)">
<a v-bind:ref="'key' + item.id" v-bind:href="item.url">
<!-- content -->
</a>
</li>
</ul>
and in Vue component you can use
var recordingModel = new Vue({
el:'#rec-container',
data:{
items:[]
},
methods:{
play:function(key,e){
// it contains the bound reference
console.log(this.$refs['item'+key]);
}
}
});
I had been wrestling with this for some time; the answers using SoftReferences would lose their data too quickly. The answers that suggest instantiating a RequestCache were too messy, plus I could never find a full example.
But ImageDownloader.java works wonderfully for me. It uses a HashMap until the capacity is reached or until the purge timeout occurs, then things get moved to a SoftReference, thereby using the best of both worlds.
Adding additional information to emboss's answer.
To put it simply, there is an incorrect cert in your certificate chain.
For example, your certificate authority will have most likely given you 3 files.
You most likely combined all of these files into one bundle.
-----BEGIN CERTIFICATE-----
(Your Primary SSL certificate: your_domain_name.crt)
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
(Your Intermediate certificate: DigiCertCA.crt)
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
(Your Root certificate: TrustedRoot.crt)
-----END CERTIFICATE-----
If you create the bundle, but use an old, or an incorrect version of your Intermediate Cert (DigiCertCA.crt in my example), you will get the exact symptoms you are describing.
Redownload all certs from your certificate authority and make a fresh bundle.
You cannot have a button inside an a
tag. You can do some javascript to make it work however.
Some disadvantage of "INTERVAL '1' DAY" is that bind variables cannot be used for the number of days added. Instead, numtodsinterval can be used, like in this small example:
select trunc(sysdate) + numtodsinterval(:x, 'day') tag
from dual
See also: NUMTODSINTERVAL in Oracle Database Online Documentation
The link you are referring to seems to work with strings generated at runtime. The strings from strings.xml are not created at runtime. You can get them via
String mystring = getResources().getString(R.string.mystring);
getResources()
is a method of the Context
class. If you are inside a Activity
or a Service
(which extend Context) you can use it like in this snippet.
Also note that the whole language dependency can be taken care of by the android framework.
Simply create different folders for each language. If english is your default language, just put the english strings into res/values/strings.xml
. Then create a new folder values-ru
and put the russian strings with identical names into res/values-ru/strings.xml
. From this point on android selects the correct one depending on the device locale for you, either when you call getString()
or when referencing strings in XML via @string/mystring
.
The ones from res/values/strings.xml
are the fallback ones, if you don't have a folder covering the users locale, this one will be used as default values.
See Localization and Providing Resources for more information.
Just use matrix
:
matrix(vec,nrow = 7,ncol = 7)
One advantage of using matrix
rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow
argument in matrix
.
My recipe of symmetric difference between two dictionaries:
def find_dict_diffs(dict1, dict2):
unequal_keys = []
unequal_keys.extend(set(dict1.keys()).symmetric_difference(set(dict2.keys())))
for k in dict1.keys():
if dict1.get(k, 'N\A') != dict2.get(k, 'N\A'):
unequal_keys.append(k)
if unequal_keys:
print 'param', 'dict1\t', 'dict2'
for k in set(unequal_keys):
print str(k)+'\t'+dict1.get(k, 'N\A')+'\t '+dict2.get(k, 'N\A')
else:
print 'Dicts are equal'
dict1 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}
dict2 = {1:'b', 2:'a', 3:'c', 4:'d', 6:'f'}
find_dict_diffs(dict1, dict2)
And result is:
param dict1 dict2
1 a b
2 b a
5 e N\A
6 N\A f
You have to wrap the entire url
statement in the bypassSecurityTrustStyle
:
<div class="header" *ngIf="image" [style.background-image]="image"></div>
And have
this.image = this.sanitization.bypassSecurityTrustStyle(`url(${element.image})`);
Otherwise it is not seen as a valid style property
As described in Cast Functions and Operators:
The type for the result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
Therefore, you should use:
SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT
first copy the cumber inside the file then remove it: rm /your_project_path/tmp/pids/server.pid then create it again. touch /YOUR_PROJECT_PATH/tmp/pids/server.pid It worked for me.
var year1 = moment().format('YYYY');_x000D_
var year2 = moment().year();_x000D_
_x000D_
console.log('using format("YYYY") : ',year1);_x000D_
console.log('using year(): ',year2);_x000D_
_x000D_
// using javascript _x000D_
_x000D_
var year3 = new Date().getFullYear();_x000D_
console.log('using javascript :',year3);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
Just wanted to summarize everything:
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<div class="unselectable" unselectable="yes" onselectstart="return false;"/>
Instead of linking to the .PDF file, instead do something like
<a href="pdf_server.php?file=pdffilename">Download my eBook</a>
which outputs a custom header, opens the PDF (binary safe) and prints the data to the user's browser, then they can choose to save the PDF despite their browser settings. The pdf_server.php should look like this:
header("Content-Type: application/octet-stream");
$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
PS: and obviously run some sanity checks on the "file" variable to prevent people from stealing your files such as don't accept file extensions, deny slashes, add .pdf to the value
I have a Mac, but luckily this should work the same way:
pip
is a command-line thing. You don't run it in python.
For example, on my Mac, I just say:
$pip install somelib
pretty easy!
You can use @BeforeClass
annotation to assure that setup()
is always called first. Similarly, you can use @AfterClass
annotation to assure that tearDown()
is always called last.
This is usually not recommended, but it is supported.
It's not exactly what you want - but it'll essentially keep your DB connection open the entire time your tests are running, and then close it once and for all at the end.
remote: Repository not found.
can be a frustratingly misleading error message from github when trying to push to an HTTPS remote where you don't have write permissions.
Trying an SSH remote to the same repository shows a different response:
% git remote add ssh [email protected]:our-organisation/some-repository.git
% git fetch ssh
From github.com:our-organisation/some-repository
* [new branch] MO_Adding_ECS_configs -> ssh/MO_Adding_ECS_configs
* [new branch] update_gems -> ssh/update_gems
% git push ssh
ERROR: Repository not found.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
"The correct access rights?"
Well why didn't you say so?
It's worth noting at this point that while the SSH failure mode in this scenario is slightly better, I use HTTPS remotes over SSH because GitHub recommend HTTPS over SSH.
I understand that GitHub uses "Not Found" where it means "Forbidden" in some circumstances to prevent inadvertently reveling the existence of a private repository.
Requests that require authentication will return
404 Not Found
, instead of403 Forbidden
, in some places. This is to prevent the accidental leakage of private repositories to unauthorized users.
--GitHub
This is a fairly common practice around the web, indeed it is defined:
The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
--6.5.4. 404 Not Found, RFC 7231 HTTP/1.1 Semantics and Content (emphasis mine)
What makes no sense to me is when I am authenticated with GitHub using a credential helper and I have access to that repository (having successfully cloned and fetched it) that GitHub would choose to hide its existence from me because of missing write permissions.
Checking https://github.com/our-organisation/some-repository/ using a web browser confirmed that I didn't have write permissions to the repository. Our team's GitHub administrators were able to grant my team write access in a short time and I was able to push the branch up.
$first = doubleval($_POST['first']);
$second = doubleval($_POST['second']);
if($_POST['group1'] == 'add') {
echo "$first + $second = ".($first + $second);
}
// etc
Programmatically, you could use:
textView.setTextAppearance(android.R.style.TextAppearance_Large);
Use eval().
W3 Schools tour of eval. Site has some usable examples of eval. The Mozilla documentation covers this in detail.
You will probably get a lot of warnings about using this safely. do NOT allow users to inject ANYTHING into eval() as it is a huge security issue.
You'll also want to know that eval() has a different scope.
This defines what shell (command interpreter) you are using for interpreting/running your script. Each shell is slightly different in the way it interacts with the user and executes scripts (programs).
When you type in a command at the Unix prompt, you are interacting with the shell.
E.g., #!/bin/csh
refers to the C-shell, /bin/tcsh
the t-shell, /bin/bash
the bash shell, etc.
You can tell which interactive shell you are using the
echo $SHELL
command, or alternatively
env | grep -i shell
You can change your command shell with the chsh
command.
Each has a slightly different command set and way of assigning variables and its own set of programming constructs. For instance the if-else statement with bash looks different that the one in the C-shell.
This page might be of interest as it "translates" between bash and tcsh commands/syntax.
Using the directive in the shell script allows you to run programs using a different shell. For instance I use the tcsh
shell interactively, but often run bash scripts using /bin/bash in the script file.
Aside:
This concept extends to other scripts too. For instance if you program in Python you'd put
#!/usr/bin/python
at the top of your Python program
Should always start with the simplest first, after wasting hours and days on this error.
And after an extensive amount of research,
Simply
RESTART YOUR MACHINE
This resolved this error.
I'm on
react-native-cli: 2.0.1
react-native: 0.63.3
I think, that in this case using PYTHONPATH is a better thing, mostly because it doesn't introduce (questionable) unneccessary code.
After all, if you think of it, your user doesn't need that sys.path
thing, because your package will get installed into site-packages, because you will be using a packaging system.
If the user chooses to run from a "local copy", as you call it, then I've observed, that the usual practice is to state, that the package needs to be added to PYTHONPATH manually, if used outside the site-packages.
This was the solution for me:
ssh-add ~/.ssh/my_heroku_key_rsa
If you try to set the DataGrid.CellStyle
the DataContext will be the row, so if you want to change the colour based on one cell it might be easiest to do so in specific columns, especially since columns can have varying contents, like TextBlocks, ComboBoxes and CheckBoxes. Here is an example of setting all the cells light-green where the Name
is John
:
<DataGridTextColumn Binding="{Binding Name}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<Trigger Property="Text" Value="John">
<Setter Property="Background" Value="LightGreen"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
You could also use a ValueConverter
to change the colour.
public class NameToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string input = value as string;
switch (input)
{
case "John":
return Brushes.LightGreen;
default:
return DependencyProperty.UnsetValue;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
Usage:
<Window.Resources>
<local:NameToBrushConverter x:Key="NameToBrushConverter"/>
</Window.Resources>
...
<DataGridTextColumn Binding="{Binding Name}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="{Binding Name, Converter={StaticResource NameToBrushConverter}}"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
Yet another option is to directly bind the Background
to a property which returns the respectively coloured brush. You will have to fire property change notifications in the setters of properties on which the colour is dependent.
e.g.
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(NameBrush));
}
}
}
public Brush NameBrush
{
get
{
switch (Name)
{
case "John":
return Brushes.LightGreen;
default:
break;
}
return Brushes.Transparent;
}
}
I know this is a very old question and there's a myriad of ways to do it. The simpler one I found is using numpy
package.
import numpy
arr = numpy.asarray([1, 6, 1, 9, 8])
arr[ arr == 8 ] = 0 # change all occurrences of 8 by 0
print(arr)
Book.java
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="Books")
public class Books implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="book_id")
private int id;
@Column(name="book_name")
private String name;
@Column(name="author_name")
private String authorName;
@ManyToOne
Subject subject;
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
}
Subject.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="Subject")
public class Subject implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="subject_id")
private int id;
@Column(name="subject_name")
private String name;
/**
Observe carefully i have mentioned fetchType.EAGER. By default its is fetchType.LAZY for @OneToMany i have mentioned it but not required. Check the Output by changing it to fetchType.EAGER
*/
@OneToMany(mappedBy="subject",cascade=CascadeType.ALL,fetch=FetchType.LAZY,
orphanRemoval=true)
List<Books> listBooks=new ArrayList<Books>();
public List<Books> getListBooks() {
return listBooks;
}
public void setListBooks(List<Books> listBooks) {
this.listBooks = listBooks;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
HibernateUtil.java
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory ;
static {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass (Com.OneToMany.Books.class);
configuration.addAnnotatedClass (Com.OneToMany.Subject.class);
configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "root");
configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.hbm2ddl.auto", "update");
configuration.setProperty("hibernate.show_sql", "true");
configuration.setProperty(" hibernate.connection.pool_size", "10");
configuration.setProperty(" hibernate.cache.use_second_level_cache", "true");
configuration.setProperty(" hibernate.cache.use_query_cache", "true");
configuration.setProperty(" cache.provider_class", "org.hibernate.cache.EhCacheProvider");
configuration.setProperty("hibernate.cache.region.factory_class" ,"org.hibernate.cache.ehcache.EhCacheRegionFactory");
// configuration
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Main.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class Main {
public static void main(String[] args) {
SessionFactory factory=HibernateUtil.getSessionFactory();
save(factory);
retrieve(factory);
}
private static void retrieve(SessionFactory factory) {
Session session=factory.openSession();
try{
session.getTransaction().begin();
Subject subject=(Subject)session.get(Subject.class, 1);
System.out.println("subject associated collection is loading lazily as @OneToMany is lazy loaded");
Books books=(Books)session.get(Books.class, 1);
System.out.println("books associated collection is loading eagerly as by default @ManyToOne is Eagerly loaded");
/*Books b1=(Books)session.get(Books.class, new Integer(1));
Subject sub=session.get(Subject.class, 1);
sub.getListBooks().remove(b1);
session.save(sub);
session.getTransaction().commit();*/
}catch(Exception e){
e.printStackTrace();
}finally{
session.close();
}
}
private static void save(SessionFactory factory){
Subject subject=new Subject();
subject.setName("C++");
Books books=new Books();
books.setAuthorName("Bala");
books.setName("C++ Book");
books.setSubject(subject);
subject.getListBooks().add(books);
Session session=factory.openSession();
try{
session.beginTransaction();
session.save(subject);
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
}finally{
session.close();
}
}
}
Check the retrieve() method of Main.java. When we get Subject, then its collection listBooks, annotated with @OneToMany
, will be loaded lazily. But, on the other hand, Books related association of collection subject, annotated with @ManyToOne
, loads eargerly (by [default][1]
for @ManyToOne
, fetchType=EAGER
). We can change the behaviour by placing fetchType.EAGER on @OneToMany
Subject.java or fetchType.LAZY on @ManyToOne
in Books.java.
DELETE
FROM m_productprice B
USING m_product C
WHERE B.m_product_id = C.m_product_id AND
C.upc = '7094' AND
B.m_pricelist_version_id='1000020';
or
DELETE
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND
m_product_id IN (SELECT m_product_id
FROM m_product
WHERE upc = '7094');
As others have said, you're not using the right function name and it doesn't exist univerally in all browsers.
If you need to do cross-browser fetching of anything other than an element with an id with document.getElementById()
, then I would strongly suggest you get a library that supports CSS3 selectors across all browsers. It will save you a massive amount of development time, testing and bug fixing. The easiest thing to do is to just use jQuery because it's so widely available, has excellent documentation, has free CDN access and has an excellent community of people behind it to answer questions. If that seems like more than you need, then you can get Sizzle which is just a selector library (it's actually the selector engine inside of jQuery and others). I've used it by itself in other projects and it's easy, productive and small.
If you want to select multiple nodes at once, you can do that many different ways. If you give them all the same class, you can do that with:
var list = document.getElementsByClassName("myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
and it will return a list of nodes that have that class name.
In Sizzle, it would be this:
var list = Sizzle(".myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
In jQuery, it would be this:
$(".myButton").each(function(index, element) {
// element is a node with the desired class name
});
In both Sizzle and jQuery, you can put multiple class names into the selector like this and use much more complicated and powerful selectors:
$(".myButton, .myInput, .homepage.gallery, #submitButton").each(function(index, element) {
// element is a node that matches the selector
});
Perhaps this will help someone.
For Android Studio 4.x Projects, you need following steps:
rootProject.name='newProjectName'
.The main answer worked for me but made the app extremely unresponsive in IE, so I used a timer as suggested. Code looks something like this ($(#contentColumn)
is the div that the JQGrid sits in):
function resizeGrids() {
var reportObjectsGrid = $("#ReportObjectsGrid");
reportObjectsGrid.setGridWidth($("#contentColumn").width());
};
var resizeTimer;
$(window).bind('resize', function () {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(resizeGrids, 60);
});
I had the same issues due to corrupted or maybe outdated intellij files. Before updating to 14.0.2 I had a perfectly working project with CORRECTLY named packages and file hierarchies.
After the update, maven compilations worked without a hitch but Intellij was reporting the said error on a specific package (other packages with similar characteristics were not affected).
I didn't bother to investigate much further , but I deleted my .iml files and .idea folders, invalidated caches, restarted the IDE, and reopened the project, relying on my maven configuration.
NOTE: This, effectively deletes run and debug configurations!
Maybe someone who understands the intellij workspace files could comment on this?
Another comment for those searching into this further: Refactoring in SC managed projects can leave behind dust -- I happen to have an "old" folder which has repetitions of the current package structure. If the .iml or .idea files have any reference to these packages it's likely that intellij could get confused with references to old packages. Good luck, fellow StackExchangers.
Update: I deleted some files in a referenced maven project and the quirk has returned. So, my post is by no means a final answer.
Within a Python scope, any assignment to a variable not already declared within that scope creates a new local variable unless that variable is declared earlier in the function as referring to a globally scoped variable with the keyword global
.
Let's look at a modified version of your pseudocode to see what happens:
# Here, we're creating a variable 'x', in the __main__ scope.
x = 'None!'
def func_A():
# The below declaration lets the function know that we
# mean the global 'x' when we refer to that variable, not
# any local one
global x
x = 'A'
return x
def func_B():
# Here, we are somewhat mislead. We're actually involving two different
# variables named 'x'. One is local to func_B, the other is global.
# By calling func_A(), we do two things: we're reassigning the value
# of the GLOBAL x as part of func_A, and then taking that same value
# since it's returned by func_A, and assigning it to a LOCAL variable
# named 'x'.
x = func_A() # look at this as: x_local = func_A()
# Here, we're assigning the value of 'B' to the LOCAL x.
x = 'B' # look at this as: x_local = 'B'
return x # look at this as: return x_local
In fact, you could rewrite all of func_B
with the variable named x_local
and it would work identically.
The order matters only as far as the order in which your functions do operations that change the value of the global x. Thus in our example, order doesn't matter, since func_B
calls func_A
. In this example, order does matter:
def a():
global foo
foo = 'A'
def b():
global foo
foo = 'B'
b()
a()
print foo
# prints 'A' because a() was the last function to modify 'foo'.
Note that global
is only required to modify global objects. You can still access them from within a function without declaring global
.
Thus, we have:
x = 5
def access_only():
return x
# This returns whatever the global value of 'x' is
def modify():
global x
x = 'modified'
return x
# This function makes the global 'x' equal to 'modified', and then returns that value
def create_locally():
x = 'local!'
return x
# This function creates a new local variable named 'x', and sets it as 'local',
# and returns that. The global 'x' is untouched.
Note the difference between create_locally
and access_only
-- access_only
is accessing the global x despite not calling global
, and even though create_locally
doesn't use global
either, it creates a local copy since it's assigning a value.
The confusion here is why you shouldn't use global variables.
You can can call a function which will calculate the iframe's body hieght when the iframe is loaded:
<script type="text/javascript">
function iframeloaded(){
var lastHeight = 0, curHeight = 0, $frame = $('iframe:eq(0)');
curHeight = $frame.contents().find('body').height();
if ( curHeight != lastHeight ) {
$frame.css('height', (lastHeight = curHeight) + 'px' );
}
}
</script>
<iframe onload="iframeloaded()" src=...>
Do it in 2 steps. First, create a dictionary.
>>> input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')]
>>> from collections import defaultdict
>>> res = defaultdict(list)
>>> for v, k in input: res[k].append(v)
...
Then, convert that dictionary into the expected format.
>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}]
It is also possible with itertools.groupby but it requires the input to be sorted first.
>>> sorted_input = sorted(input, key=itemgetter(1))
>>> groups = groupby(sorted_input, key=itemgetter(1))
>>> [{'type':k, 'items':[x[0] for x in v]} for k, v in groups]
[{'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}]
Note both of these do not respect the original order of the keys. You need an OrderedDict if you need to keep the order.
>>> from collections import OrderedDict
>>> res = OrderedDict()
>>> for v, k in input:
... if k in res: res[k].append(v)
... else: res[k] = [v]
...
>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}]
Didn't test this for IE, but if you make an element elem
with
min-width: 100%
then
window.document.width / elem.clientWidth
will give you your browser zoom level (including the document.body.style.zoom
factor).
It can be very useful a few times, but in general, no fall-through is the desired behavior. Fall-through should be allowed, but not implicit.
An example, to update old versions of some data:
switch (version) {
case 1:
// Update some stuff
case 2:
// Update more stuff
case 3:
// Update even more stuff
case 4:
// And so on
}
If you want to have the ListView in an AppCompatActivity instead of ListActivity, you can do the following (Modifying @Shardul's answer):
public class ListViewDemoActivity extends AppCompatActivity {
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems=new ArrayList<String>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
//RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
int clickCounter=0;
private ListView mListView;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_list_view_demo);
if (mListView == null) {
mListView = (ListView) findViewById(R.id.listDemo);
}
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
}
//METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void addItems(View v) {
listItems.add("Clicked : "+clickCounter++);
adapter.notifyDataSetChanged();
}
protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(R.id.listDemo);
}
return mListView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
}
And in you layout instead of using android:id="@android:id/list"
you can use android:id="@+id/listDemo"
So now you can have a ListView
inside a normal AppCompatActivity
.
How about a pure CSS solution without being (that) hacky?
.page {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
right: 0;_x000D_
left: 0;_x000D_
background-color: #121519;_x000D_
color: whitesmoke;_x000D_
}_x000D_
_x000D_
.controls {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.arrow {_x000D_
cursor: pointer;_x000D_
transition: filter 0.3s ease 0.3s;_x000D_
}_x000D_
_x000D_
.arrow:active {_x000D_
filter: drop-shadow(0 0 0 steelblue);_x000D_
transition: filter 0s;_x000D_
}
_x000D_
<body class="page">_x000D_
<div class="controls">_x000D_
<div class="arrow">_x000D_
<img src="https://i.imgur.com/JGUoNfS.png" />_x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
@TylerH has a great response but its a pretty complex solution. I have a solution for those of you that just want a simple "onclick" effect with pure css without a bunch of extra elements.
We will simply use css transitions. You could probably do similar with animations.
The trick is to change the delay for the transition so that it will last when the user clicks.
.arrowDownContainer:active,
.arrowDownContainer.clicked {
filter: drop-shadow(0px 0px 0px steelblue);
transition: filter 0s;
}
Here I add the "clicked" class as well so that javascript can also provide the effect if it needs to. I use 0px drop-shadow filter because it will highlight the given transparent graphic blue this way for my case.
I have a filter at 0s here so that it wont take effect. When the effect is released I can then add the transition with a delay so that it will provide a nice "clicked" effect.
.arrowDownContainer {
cursor: pointer;
position: absolute;
bottom: 0px;
top: 490px;
left: 108px;
height: 222px;
width: 495px;
z-index: 3;
transition: filter 0.3s ease 0.3s;
}
This allows me to set it up so that when the user clicks the button, it highlights blue then fades out slowly (you could, of course, use other effects as well).
While you are limited here in the sense that the animation to highlight is instant, it does still provide the desired effect. You could likely use this trick with animation to produce a smoother overall transition.
A few bullet points from a previous answer:
Most important: Does the sender address ("From") belong to a domain that runs on the server you send the E-Mail from? If not, make it so. Never use sender addresses like [email protected]
. User reply-to
if you need replies to arrive at a different address.
Is your server on a blacklist (e.g. check IP on spamhaus.org)? This is a possibility when you're on shared hosting when neighbours behave badly.
Are mails filtered by a spam filter? Open an account with a freemailer that has a spam folder and find out. Also, try sending mail to an address without any spam filtering at all.
Do you possibly need the fifth parameter "-f" of mail() to add a sender address? (See mail() command in the PHP manual)
If you have access to log files, check those, of course.
First write properly. You want to navigate within an application for another link from your application for another link. Here is the code:
window.location.href = "http://www.google.com";
And if you want to navigate pages within your application then I also have code, if you want.
If you are trying to use below example
Example: { value1: "value1" }
And add conditionalData dynamically based on some condition, Try
let dataToWrite: any = {value1: "value1"};
if(conditionalData)
dataToWrite["conditionalData"] = conditionalData