qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
30,031,388 | I'd like to know about other patterns that could be more efficient than the use of factories. | 2015/05/04 | [
"https://Stackoverflow.com/questions/30031388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4333314/"
]
| You could use a memory pool, the boost one is pretty good:
<http://www.boost.org/doc/libs/1_58_0/libs/pool/doc/html/boost_pool/pool.html>
And every client could configure the maximum size of the pool.
Allocations and deallocations will be really fast,and you will drop your factory implementation | Measure first. If you haven't proved that your allocator is a performance problem then you shouldn't optimize it away. Your solution to not free memory back may in fact perform worse (e.g., if you're using a simple free-list, you might be spending a lot of time on cache misses when you traverse the list).
If memory allocation is a bottleneck, look into better allocators. TCMalloc is pretty good, and there are commercial and cross-platform solutions available if you want to pay lots of money.
But use a profiler and measure before you do anything drastic. |
18,718,469 | I have a search method in `User` model. But I can search only by User columns. User `belongs_to` Company model.
**Question:** I want to search users by `user.company.name` too. How can I do this?
user.rb
```
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation, :developer, :admin, :company_id, :boss_id, :company
belongs_to :company
def self.search(search)
if search
q = "%#{search}%"
where('name LIKE ? OR
company_id LIKE ?',
q,q)
else
scoped
end
end
end
```
index.html.erb
```
<% provide(:title, 'Users') %>
<h1>Users</h1>
<%= form_tag users_path, :method => 'get' do %>
<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
```
users\_controller.rb
```
class UsersController < ApplicationController
def index
@users = User.where(:developer => false, :admin => false).search(params[:search]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 10, :page => params[:page])
end
end
``` | 2013/09/10 | [
"https://Stackoverflow.com/questions/18718469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2702786/"
]
| Try This
```
def self.search(search)
if search
q = "%#{search}%"
joins(:company).where('users.name LIKE ? OR
companies.name LIKE ?',q,q)
else
scoped
end
end
``` | ```
@users = User.joins(:company).where(companies: {name: name}, developer: false, admin: false)
```
Now you only need to input your company name into parameters. |
21,154,462 | I want to rename a series of .jpg but i want to append the string at the end of file name. Please help me how can I achive this as I am new to batch file coding.
**Series of jpg files** -
CurDt\_S1, CurDt\_S2, CurDt\_S3 etc.. uptill S20.
**I want to replace CurDt\_S1 with CurDt\_1\_S1 as -**
CurDt\_1\_S1, CurDt\_1\_S2, CurDt\_1\_S3 uptill S20.
**Here is the code I am using -**
```
setlocal enabledelayedexpansion
set str=_1
for %%a in (CurDt_S*.jpg) do (
set oldName=%%a
set newName=oldname+str
call :Action
echo.
echo back in For loop
)
echo.
echo For loop completed
echo !oldName!
echo !newName!
endlocal
goto:eof
:Action
echo.
echo start of Action loop
echo !oldName!
echo !newName!
ren "!oldName!" "!newName!"
echo end of Action loop
```
Thanks,
Sneha | 2014/01/16 | [
"https://Stackoverflow.com/questions/21154462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742601/"
]
| Here is the simplest way I can think of:
```
@echo off
set i=1
for %%f in (CurDt_S*.jpg) do call :renameit "%%f"
goto done
:renameit
ren CurDt_S%i%.jpg CurDt_1_S%i%.jpg
set /A i+=1
:done
```
It assumes the batch files are located in the same directory as the jpg files.
Hope this helps. | ```
for %%f in ("c:\somewhere\CurDt_*.jpg") do (
for /f "tokens=1,* delims=_" %%g in ("%%~nf") do echo ren "%%~ff" "%%~g_1_%%~h%%~xf"
)
```
For each of the indicated files, split the name of the file using the first underscore as delimiter to get the two parts, and rename the file to the the first token + `_1_` + second token + file extension.
Result is only echoed to console. If output is correct, remove `echo` command to rename the files. |
21,154,462 | I want to rename a series of .jpg but i want to append the string at the end of file name. Please help me how can I achive this as I am new to batch file coding.
**Series of jpg files** -
CurDt\_S1, CurDt\_S2, CurDt\_S3 etc.. uptill S20.
**I want to replace CurDt\_S1 with CurDt\_1\_S1 as -**
CurDt\_1\_S1, CurDt\_1\_S2, CurDt\_1\_S3 uptill S20.
**Here is the code I am using -**
```
setlocal enabledelayedexpansion
set str=_1
for %%a in (CurDt_S*.jpg) do (
set oldName=%%a
set newName=oldname+str
call :Action
echo.
echo back in For loop
)
echo.
echo For loop completed
echo !oldName!
echo !newName!
endlocal
goto:eof
:Action
echo.
echo start of Action loop
echo !oldName!
echo !newName!
ren "!oldName!" "!newName!"
echo end of Action loop
```
Thanks,
Sneha | 2014/01/16 | [
"https://Stackoverflow.com/questions/21154462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742601/"
]
| ```
for /L %%x in (1,1,20) do ECHO ren CurDt_S%%x.jpg CurDt_1_S%%x.jpg
```
should work for you.
The required commands are merely `ECHO`ed for testing purposes. After you've verified that the commands are correct, change `ECHO REN` to `REN` to actually rename the files. | Here is the simplest way I can think of:
```
@echo off
set i=1
for %%f in (CurDt_S*.jpg) do call :renameit "%%f"
goto done
:renameit
ren CurDt_S%i%.jpg CurDt_1_S%i%.jpg
set /A i+=1
:done
```
It assumes the batch files are located in the same directory as the jpg files.
Hope this helps. |
21,154,462 | I want to rename a series of .jpg but i want to append the string at the end of file name. Please help me how can I achive this as I am new to batch file coding.
**Series of jpg files** -
CurDt\_S1, CurDt\_S2, CurDt\_S3 etc.. uptill S20.
**I want to replace CurDt\_S1 with CurDt\_1\_S1 as -**
CurDt\_1\_S1, CurDt\_1\_S2, CurDt\_1\_S3 uptill S20.
**Here is the code I am using -**
```
setlocal enabledelayedexpansion
set str=_1
for %%a in (CurDt_S*.jpg) do (
set oldName=%%a
set newName=oldname+str
call :Action
echo.
echo back in For loop
)
echo.
echo For loop completed
echo !oldName!
echo !newName!
endlocal
goto:eof
:Action
echo.
echo start of Action loop
echo !oldName!
echo !newName!
ren "!oldName!" "!newName!"
echo end of Action loop
```
Thanks,
Sneha | 2014/01/16 | [
"https://Stackoverflow.com/questions/21154462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742601/"
]
| Here is the simplest way I can think of:
```
@echo off
set i=1
for %%f in (CurDt_S*.jpg) do call :renameit "%%f"
goto done
:renameit
ren CurDt_S%i%.jpg CurDt_1_S%i%.jpg
set /A i+=1
:done
```
It assumes the batch files are located in the same directory as the jpg files.
Hope this helps. | I am using following code to rename the files. Basically, it would be as follows -
CurDt\_S1 will be renamed as CurDt\_1\_S1 uptill S20,
CurDt\_1\_S1 to CurDt\_2\_S1 uptill S20,
CurDt\_2\_S1 to CurDt\_3\_S1 uptill S20,
CurDt\_3\_S1 to CurDt\_4\_S1 uptill S20,
and CurDt\_4\_S1 files will be archived to a diff folder.
Code is as follows-
set i=1
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_4\_S\*.jpg") do call :currentdate4 "%%f"
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_3\_S\*.jpg") do call :currentdate3 "%%f"
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_2\_S\*.jpg") do call :currentdate2 "%%f"
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_1\_S\*.jpg") do call :currentdate1 "%%f"
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_S\*.jpg") do call :currentdate "%%f"
goto done
exit
```
:currentdate4
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_4_S*.jpg (
rem move C:\Users\341256\Desktop\test_batch_files\CurDt_4_S*.jpg C:\Users\341256\Desktop\test_batch_files\Archive
echo moved current_date-4 files )
:currentdate3
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_3_S*.jpg (
ren CurDt_3_S%i%.jpg CurDt_4_S%i%.jpg
echo renamed _3 to _4 )
:currentdate2
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_2_S*.jpg (
ren CurDt_2_S%i%.jpg CurDt_3_S%i%.jpg
echo renamed _2 to _3 )
:currentdate1
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_1_S*.jpg (
ren CurDt_1_S%i%.jpg CurDt_2_S%i%.jpg
echo renamed _1 to _2 )
:currentdate
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_S*.jpg (
ren CurDt_S%i%.jpg CurDt_1_S%i%.jpg
echo renamed currdt to _1
echo complete )
set /A i+=1
:done
pause
```
Please suggest if it is right.
Thanks,
Sneha |
21,154,462 | I want to rename a series of .jpg but i want to append the string at the end of file name. Please help me how can I achive this as I am new to batch file coding.
**Series of jpg files** -
CurDt\_S1, CurDt\_S2, CurDt\_S3 etc.. uptill S20.
**I want to replace CurDt\_S1 with CurDt\_1\_S1 as -**
CurDt\_1\_S1, CurDt\_1\_S2, CurDt\_1\_S3 uptill S20.
**Here is the code I am using -**
```
setlocal enabledelayedexpansion
set str=_1
for %%a in (CurDt_S*.jpg) do (
set oldName=%%a
set newName=oldname+str
call :Action
echo.
echo back in For loop
)
echo.
echo For loop completed
echo !oldName!
echo !newName!
endlocal
goto:eof
:Action
echo.
echo start of Action loop
echo !oldName!
echo !newName!
ren "!oldName!" "!newName!"
echo end of Action loop
```
Thanks,
Sneha | 2014/01/16 | [
"https://Stackoverflow.com/questions/21154462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742601/"
]
| I finally figured out the **SIMPLEST way** to achieve this by using **BATCH in simplest way.**
By Using following code -
```
del CurDt_5_S*
ren CurDt_4_S* CurDt_5_S*
ren CurDt_3_S* CurDt_4_S*
ren CurDt_2_S* CurDt_3_S*
ren CurDt_1_S* CurDt_2_S*
```
I tested it and its working. :) :) :) | Here is the simplest way I can think of:
```
@echo off
set i=1
for %%f in (CurDt_S*.jpg) do call :renameit "%%f"
goto done
:renameit
ren CurDt_S%i%.jpg CurDt_1_S%i%.jpg
set /A i+=1
:done
```
It assumes the batch files are located in the same directory as the jpg files.
Hope this helps. |
21,154,462 | I want to rename a series of .jpg but i want to append the string at the end of file name. Please help me how can I achive this as I am new to batch file coding.
**Series of jpg files** -
CurDt\_S1, CurDt\_S2, CurDt\_S3 etc.. uptill S20.
**I want to replace CurDt\_S1 with CurDt\_1\_S1 as -**
CurDt\_1\_S1, CurDt\_1\_S2, CurDt\_1\_S3 uptill S20.
**Here is the code I am using -**
```
setlocal enabledelayedexpansion
set str=_1
for %%a in (CurDt_S*.jpg) do (
set oldName=%%a
set newName=oldname+str
call :Action
echo.
echo back in For loop
)
echo.
echo For loop completed
echo !oldName!
echo !newName!
endlocal
goto:eof
:Action
echo.
echo start of Action loop
echo !oldName!
echo !newName!
ren "!oldName!" "!newName!"
echo end of Action loop
```
Thanks,
Sneha | 2014/01/16 | [
"https://Stackoverflow.com/questions/21154462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742601/"
]
| ```
for /L %%x in (1,1,20) do ECHO ren CurDt_S%%x.jpg CurDt_1_S%%x.jpg
```
should work for you.
The required commands are merely `ECHO`ed for testing purposes. After you've verified that the commands are correct, change `ECHO REN` to `REN` to actually rename the files. | ```
for %%f in ("c:\somewhere\CurDt_*.jpg") do (
for /f "tokens=1,* delims=_" %%g in ("%%~nf") do echo ren "%%~ff" "%%~g_1_%%~h%%~xf"
)
```
For each of the indicated files, split the name of the file using the first underscore as delimiter to get the two parts, and rename the file to the the first token + `_1_` + second token + file extension.
Result is only echoed to console. If output is correct, remove `echo` command to rename the files. |
21,154,462 | I want to rename a series of .jpg but i want to append the string at the end of file name. Please help me how can I achive this as I am new to batch file coding.
**Series of jpg files** -
CurDt\_S1, CurDt\_S2, CurDt\_S3 etc.. uptill S20.
**I want to replace CurDt\_S1 with CurDt\_1\_S1 as -**
CurDt\_1\_S1, CurDt\_1\_S2, CurDt\_1\_S3 uptill S20.
**Here is the code I am using -**
```
setlocal enabledelayedexpansion
set str=_1
for %%a in (CurDt_S*.jpg) do (
set oldName=%%a
set newName=oldname+str
call :Action
echo.
echo back in For loop
)
echo.
echo For loop completed
echo !oldName!
echo !newName!
endlocal
goto:eof
:Action
echo.
echo start of Action loop
echo !oldName!
echo !newName!
ren "!oldName!" "!newName!"
echo end of Action loop
```
Thanks,
Sneha | 2014/01/16 | [
"https://Stackoverflow.com/questions/21154462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742601/"
]
| I finally figured out the **SIMPLEST way** to achieve this by using **BATCH in simplest way.**
By Using following code -
```
del CurDt_5_S*
ren CurDt_4_S* CurDt_5_S*
ren CurDt_3_S* CurDt_4_S*
ren CurDt_2_S* CurDt_3_S*
ren CurDt_1_S* CurDt_2_S*
```
I tested it and its working. :) :) :) | ```
for %%f in ("c:\somewhere\CurDt_*.jpg") do (
for /f "tokens=1,* delims=_" %%g in ("%%~nf") do echo ren "%%~ff" "%%~g_1_%%~h%%~xf"
)
```
For each of the indicated files, split the name of the file using the first underscore as delimiter to get the two parts, and rename the file to the the first token + `_1_` + second token + file extension.
Result is only echoed to console. If output is correct, remove `echo` command to rename the files. |
21,154,462 | I want to rename a series of .jpg but i want to append the string at the end of file name. Please help me how can I achive this as I am new to batch file coding.
**Series of jpg files** -
CurDt\_S1, CurDt\_S2, CurDt\_S3 etc.. uptill S20.
**I want to replace CurDt\_S1 with CurDt\_1\_S1 as -**
CurDt\_1\_S1, CurDt\_1\_S2, CurDt\_1\_S3 uptill S20.
**Here is the code I am using -**
```
setlocal enabledelayedexpansion
set str=_1
for %%a in (CurDt_S*.jpg) do (
set oldName=%%a
set newName=oldname+str
call :Action
echo.
echo back in For loop
)
echo.
echo For loop completed
echo !oldName!
echo !newName!
endlocal
goto:eof
:Action
echo.
echo start of Action loop
echo !oldName!
echo !newName!
ren "!oldName!" "!newName!"
echo end of Action loop
```
Thanks,
Sneha | 2014/01/16 | [
"https://Stackoverflow.com/questions/21154462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742601/"
]
| ```
for /L %%x in (1,1,20) do ECHO ren CurDt_S%%x.jpg CurDt_1_S%%x.jpg
```
should work for you.
The required commands are merely `ECHO`ed for testing purposes. After you've verified that the commands are correct, change `ECHO REN` to `REN` to actually rename the files. | I am using following code to rename the files. Basically, it would be as follows -
CurDt\_S1 will be renamed as CurDt\_1\_S1 uptill S20,
CurDt\_1\_S1 to CurDt\_2\_S1 uptill S20,
CurDt\_2\_S1 to CurDt\_3\_S1 uptill S20,
CurDt\_3\_S1 to CurDt\_4\_S1 uptill S20,
and CurDt\_4\_S1 files will be archived to a diff folder.
Code is as follows-
set i=1
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_4\_S\*.jpg") do call :currentdate4 "%%f"
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_3\_S\*.jpg") do call :currentdate3 "%%f"
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_2\_S\*.jpg") do call :currentdate2 "%%f"
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_1\_S\*.jpg") do call :currentdate1 "%%f"
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_S\*.jpg") do call :currentdate "%%f"
goto done
exit
```
:currentdate4
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_4_S*.jpg (
rem move C:\Users\341256\Desktop\test_batch_files\CurDt_4_S*.jpg C:\Users\341256\Desktop\test_batch_files\Archive
echo moved current_date-4 files )
:currentdate3
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_3_S*.jpg (
ren CurDt_3_S%i%.jpg CurDt_4_S%i%.jpg
echo renamed _3 to _4 )
:currentdate2
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_2_S*.jpg (
ren CurDt_2_S%i%.jpg CurDt_3_S%i%.jpg
echo renamed _2 to _3 )
:currentdate1
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_1_S*.jpg (
ren CurDt_1_S%i%.jpg CurDt_2_S%i%.jpg
echo renamed _1 to _2 )
:currentdate
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_S*.jpg (
ren CurDt_S%i%.jpg CurDt_1_S%i%.jpg
echo renamed currdt to _1
echo complete )
set /A i+=1
:done
pause
```
Please suggest if it is right.
Thanks,
Sneha |
21,154,462 | I want to rename a series of .jpg but i want to append the string at the end of file name. Please help me how can I achive this as I am new to batch file coding.
**Series of jpg files** -
CurDt\_S1, CurDt\_S2, CurDt\_S3 etc.. uptill S20.
**I want to replace CurDt\_S1 with CurDt\_1\_S1 as -**
CurDt\_1\_S1, CurDt\_1\_S2, CurDt\_1\_S3 uptill S20.
**Here is the code I am using -**
```
setlocal enabledelayedexpansion
set str=_1
for %%a in (CurDt_S*.jpg) do (
set oldName=%%a
set newName=oldname+str
call :Action
echo.
echo back in For loop
)
echo.
echo For loop completed
echo !oldName!
echo !newName!
endlocal
goto:eof
:Action
echo.
echo start of Action loop
echo !oldName!
echo !newName!
ren "!oldName!" "!newName!"
echo end of Action loop
```
Thanks,
Sneha | 2014/01/16 | [
"https://Stackoverflow.com/questions/21154462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742601/"
]
| I finally figured out the **SIMPLEST way** to achieve this by using **BATCH in simplest way.**
By Using following code -
```
del CurDt_5_S*
ren CurDt_4_S* CurDt_5_S*
ren CurDt_3_S* CurDt_4_S*
ren CurDt_2_S* CurDt_3_S*
ren CurDt_1_S* CurDt_2_S*
```
I tested it and its working. :) :) :) | I am using following code to rename the files. Basically, it would be as follows -
CurDt\_S1 will be renamed as CurDt\_1\_S1 uptill S20,
CurDt\_1\_S1 to CurDt\_2\_S1 uptill S20,
CurDt\_2\_S1 to CurDt\_3\_S1 uptill S20,
CurDt\_3\_S1 to CurDt\_4\_S1 uptill S20,
and CurDt\_4\_S1 files will be archived to a diff folder.
Code is as follows-
set i=1
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_4\_S\*.jpg") do call :currentdate4 "%%f"
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_3\_S\*.jpg") do call :currentdate3 "%%f"
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_2\_S\*.jpg") do call :currentdate2 "%%f"
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_1\_S\*.jpg") do call :currentdate1 "%%f"
for %%f in ("C:\Users\341256\Desktop\test\_batch\_files\CurDt\_S\*.jpg") do call :currentdate "%%f"
goto done
exit
```
:currentdate4
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_4_S*.jpg (
rem move C:\Users\341256\Desktop\test_batch_files\CurDt_4_S*.jpg C:\Users\341256\Desktop\test_batch_files\Archive
echo moved current_date-4 files )
:currentdate3
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_3_S*.jpg (
ren CurDt_3_S%i%.jpg CurDt_4_S%i%.jpg
echo renamed _3 to _4 )
:currentdate2
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_2_S*.jpg (
ren CurDt_2_S%i%.jpg CurDt_3_S%i%.jpg
echo renamed _2 to _3 )
:currentdate1
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_1_S*.jpg (
ren CurDt_1_S%i%.jpg CurDt_2_S%i%.jpg
echo renamed _1 to _2 )
:currentdate
if exist C:\Users\341256\Desktop\test_batch_files\CurDt_S*.jpg (
ren CurDt_S%i%.jpg CurDt_1_S%i%.jpg
echo renamed currdt to _1
echo complete )
set /A i+=1
:done
pause
```
Please suggest if it is right.
Thanks,
Sneha |
865,466 | I was on Office 2010 and got asked to be in the pilot group for Office 365. After this period O365 went live and I deemed it a good idea to uninstall Office 2010.
After this was done all Office related filetypes lost their association with office and excel woorkbooks were always opened as a blank file.
Since repairing the installation did not resolve the issue I tried uninstalling. Since Office 365 is installed as 10 different products (1 for each language) on my machine I have to uninstall one by one.
After I uninstalled to de-DE version, which is my native locale, everyting worked again in en-US. Here comes my problem: How can I re-install the German language pack or uninstall Office 365 in a one-click manner completly to get it re-installed from the system center from scratch?
I can't just go to the System center configruation manager and click install. The system then will tell me, that office is already installed. If I uninstall everything by hand, I have to calculate about 2 hours per language pack at current performance of my hard drive. | 2015/01/16 | [
"https://superuser.com/questions/865466",
"https://superuser.com",
"https://superuser.com/users/275822/"
]
| You can open `viber.db` in `C:\Users\USERNAME\AppData\Roaming\ViberPC\YourNumber` with WordPad and somewhere in the beginning of the file you will find contacts phone numbers. Just enter them manually in your new phone and they will appear on you contacts list in Viber.
Or download [command-line shell for accessing and modifying SQLite databases](http://www.sqlite.org/download.html) and copy `sqlite3.exe` , `viber.db` and `data.db` to `C:\`. Then in CMD(start -> run -> cmd.exe) position yourself on `C:\` and enter `sqlite3.exe viber.db`
Then enter:
```
SELECT ContactRelation.Number, Contact.FirstName, Contact.SecondName FROM Contact INNER JOIN ContactRelation ON Contact.ContactID = ContactRelation.ContactID ORDER BY Contact.FirstName;
```
There you go! You got all contacts listed, phone number first and then the name! | Maybe the data base structure has changed, in my case, I had to slightly change @Davidenko's instructions.
Install a SQLite command-line shell, perhaps from here [sqlite.org/download.html](https://www.sqlite.org/download.html). It is bundled in the sqlite-tools.
Copy the file
```
C:\Users\USERNAME\AppData\Roaming\ViberPC\YourNumber\viber.db
```
somewhere. Now in PowerShell or CMD `cd` to `viber.db` directory and open it with:
```
sqlite3 .\viber.db
```
That opens `viber.db` in the SQLite shell.
**To export contacts as a CSV** file, write in the SQL shell:
```
.mode csv
.output contacts.csv
SELECT Contact.Name, Contact.Number, Contact.ViberContact FROM Contact;
.output stdout
```
**To export text messages as a CSV** including related contacts, write:
```
.mode csv
.output messages.csv
SELECT Contact.Name, Contact.Number, Contact.ViberContact, Events.TimeStamp, Messages.Body FROM Contact INNER JOIN Events ON Contact.ContactID = Events.ContactID INNER JOIN Messages ON Events.EventID = Messages.EventID ORDER BY Contact.Name;
.output stdout
``` |
865,466 | I was on Office 2010 and got asked to be in the pilot group for Office 365. After this period O365 went live and I deemed it a good idea to uninstall Office 2010.
After this was done all Office related filetypes lost their association with office and excel woorkbooks were always opened as a blank file.
Since repairing the installation did not resolve the issue I tried uninstalling. Since Office 365 is installed as 10 different products (1 for each language) on my machine I have to uninstall one by one.
After I uninstalled to de-DE version, which is my native locale, everyting worked again in en-US. Here comes my problem: How can I re-install the German language pack or uninstall Office 365 in a one-click manner completly to get it re-installed from the system center from scratch?
I can't just go to the System center configruation manager and click install. The system then will tell me, that office is already installed. If I uninstall everything by hand, I have to calculate about 2 hours per language pack at current performance of my hard drive. | 2015/01/16 | [
"https://superuser.com/questions/865466",
"https://superuser.com",
"https://superuser.com/users/275822/"
]
| You can open `viber.db` in `C:\Users\USERNAME\AppData\Roaming\ViberPC\YourNumber` with WordPad and somewhere in the beginning of the file you will find contacts phone numbers. Just enter them manually in your new phone and they will appear on you contacts list in Viber.
Or download [command-line shell for accessing and modifying SQLite databases](http://www.sqlite.org/download.html) and copy `sqlite3.exe` , `viber.db` and `data.db` to `C:\`. Then in CMD(start -> run -> cmd.exe) position yourself on `C:\` and enter `sqlite3.exe viber.db`
Then enter:
```
SELECT ContactRelation.Number, Contact.FirstName, Contact.SecondName FROM Contact INNER JOIN ContactRelation ON Contact.ContactID = ContactRelation.ContactID ORDER BY Contact.FirstName;
```
There you go! You got all contacts listed, phone number first and then the name! | On **ubuntu** I found it under:
* `/home/[user]/snap/viber-unofficial/37/.ViberPC/[phonenumber]/viber.db` (snap installation)
* `/home/[user]/.ViberPC/[phonenumber]/viber.db` (non-snap installation)
Then you can open with `sqlitebrowser`
```bsh
sudo apt install sqlitebrowser
sqlitebrowser viber.db
``` |
865,466 | I was on Office 2010 and got asked to be in the pilot group for Office 365. After this period O365 went live and I deemed it a good idea to uninstall Office 2010.
After this was done all Office related filetypes lost their association with office and excel woorkbooks were always opened as a blank file.
Since repairing the installation did not resolve the issue I tried uninstalling. Since Office 365 is installed as 10 different products (1 for each language) on my machine I have to uninstall one by one.
After I uninstalled to de-DE version, which is my native locale, everyting worked again in en-US. Here comes my problem: How can I re-install the German language pack or uninstall Office 365 in a one-click manner completly to get it re-installed from the system center from scratch?
I can't just go to the System center configruation manager and click install. The system then will tell me, that office is already installed. If I uninstall everything by hand, I have to calculate about 2 hours per language pack at current performance of my hard drive. | 2015/01/16 | [
"https://superuser.com/questions/865466",
"https://superuser.com",
"https://superuser.com/users/275822/"
]
| Maybe the data base structure has changed, in my case, I had to slightly change @Davidenko's instructions.
Install a SQLite command-line shell, perhaps from here [sqlite.org/download.html](https://www.sqlite.org/download.html). It is bundled in the sqlite-tools.
Copy the file
```
C:\Users\USERNAME\AppData\Roaming\ViberPC\YourNumber\viber.db
```
somewhere. Now in PowerShell or CMD `cd` to `viber.db` directory and open it with:
```
sqlite3 .\viber.db
```
That opens `viber.db` in the SQLite shell.
**To export contacts as a CSV** file, write in the SQL shell:
```
.mode csv
.output contacts.csv
SELECT Contact.Name, Contact.Number, Contact.ViberContact FROM Contact;
.output stdout
```
**To export text messages as a CSV** including related contacts, write:
```
.mode csv
.output messages.csv
SELECT Contact.Name, Contact.Number, Contact.ViberContact, Events.TimeStamp, Messages.Body FROM Contact INNER JOIN Events ON Contact.ContactID = Events.ContactID INNER JOIN Messages ON Events.EventID = Messages.EventID ORDER BY Contact.Name;
.output stdout
``` | On **ubuntu** I found it under:
* `/home/[user]/snap/viber-unofficial/37/.ViberPC/[phonenumber]/viber.db` (snap installation)
* `/home/[user]/.ViberPC/[phonenumber]/viber.db` (non-snap installation)
Then you can open with `sqlitebrowser`
```bsh
sudo apt install sqlitebrowser
sqlitebrowser viber.db
``` |
68,464,729 | Goodday,
I have 2 sheets. For each ID on sheet1 I need to verify if that ID is also on sheet2 AND if Date Processed is blank.
If both condition are true > today's date should be set in Date Processed.
[](https://i.stack.imgur.com/Wvet0.png)
I've managed to do so for just 1 value (A2) from sheet1.
What I need is a way to go through all the values in sheet1. Ideally the row in sheet1 would also get deleted (not sure if that is possible)
This is my code till now
```
function myMatch(){
var file = SpreadsheetApp.getActiveSpreadsheet();
var ss = file.getSheetByName("Sheet1");
var ws = file.getSheetByName("Sheet2");
var wsData = ws.getDataRange().getValues();
var mySearch = ss.getRange("A2").getValue();
for(var i = 0; i < wsData.length; i++){
if(wsData[i][1] == mySearch && wsData[i][2] == "")
{
ws.getRange(i+1,3).setNumberFormat('dd"-"mmm"-"yyyy').setValue(new Date());
}
}
}
```
Your help is really appreciated as I have been trying and searching for a solution for 2 days now. Thank you | 2021/07/21 | [
"https://Stackoverflow.com/questions/68464729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15972586/"
]
| I know it doesn't makes much sense. Muhammet's code works and looks just fine. But, rather for fun and educational purposes, here is another "functional" solution:
```
function myFunction() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const s1 = ss.getSheetByName('Sheet1');
const s2 = ss.getSheetByName('Sheet2');
// get data from Sheet1 and Sheet2
const s1_data = s1.getDataRange().getValues().slice(1,);
const s2_data = s2.getDataRange().getValues().slice(1,);
// get IDs from data of Sheet1
const IDs = s1_data.map(x => x[0]);
const IDs_to_delete = []; // here will be IDs to delete
// function checks and fill a row and adds ID to array to delete
const write_date = (id,row) => {
if (row[1] == id && row[2] == '') {
IDs_to_delete.push(id);
row[2] = new Date();
}
}
// change rows within data of Sheet 2
IDs.forEach(id => s2_data.forEach(row => row = write_date(id,row)));
// clear and fill Sheet 2
s2.getDataRange().offset(1,0).clearContent();
s2.getRange(2,1,s2_data.length,s2_data[0].length).setValues(s2_data);
// remove rows from data of Sheet 1
const s1_data_new = s1_data.filter(row => !IDs_to_delete.includes(row[0]));
// clear and fill Sheet 1 with new data
s1.getDataRange().offset(1,0).clearContent();
s1.getRange(2,1,s1_data_new.length,s1_data_new[0].length).setValues(s1_data_new);
}
```
The only improvements over Muhamed's code is that this implementation removes processed rows from Sheet1. And, I believe, it will work faster for huge lists, because it doesn't use `getRange()` and `setValue()` on every found cell but fills all cells of the sheet at once with `setValues()` method. | You need a loop for this. Use
>
> var mySearchs = ss.getRange('A2:A').getValues();
>
>
>
and loop through all values of this array.
```
function myMatch(){
var file = SpreadsheetApp.getActiveSpreadsheet();
var ss = file.getSheetByName("Sheet1");
var ws = file.getSheetByName("Sheet2");
var wsData = ws.getDataRange().getValues();
var mySearchs = ss.getRange('A2:A').getValues();
mySearchs.forEach((v) => {
for(var i = 0; i < wsData.length; i++){
if(wsData[i][1] == v && wsData[i][2] == "")
{
ws.getRange(i+1,3).setNumberFormat('dd"-"mmm"-"yyyy').setValue(new Date());
}
}
})
}
``` |
33,316,924 | I am trying to make a slider which scrolls over 3 div elements on to 3 new scroll elements. I am looking for a manual slider with an arrow pointing right on the right side and left on the left side. The slider should slide right when right arrow clicked and display the 3 remaining div elements. If the left arrow is clicked first, nothing should happen. if it is clicked after the right arrow has been clicked it should slide back to the three previous div elements. If the right arrow is clicked twice in a row the second click should slide back to the initial 3 div elements. Basically, I want to end up with something like the slider on the unity website. Link: <http://unity3d.com/unity>
Here is my HTML code so far. It displays the boxes on 3 columns and 2 rows:
```
<div class="categories">
<div class="category">
<div class="rect">
<img src="stuff.gif">
</div>
<h3>Stuff</h3>
<p>Stuff.</p>
</div>
<div class="category">
<div class="rect">
<img src="stuff.gif">
</div>
<h3>Stuff</h3>
<p>Stuff.</p>
</div>
<div class="category">
<div class="rect">
<img src="stuff.gif">
</div>
<h3>Stuff</h3>
<p>Stuff.</p>
</div>
<div class="category">
<div class="rect">
<img src="stuff.gif">
</div>
<h3>Stuff</h3>
<p>Stuff.</p>
</div>
<div class="category">
<div class="rect">
<img src="stuff.gif">
</div>
<h3>Stuff</h3>
<p>Stuff.</p>
</div>
<div class="category">
<div class="rect">
<img src="stuff.gif">
</div>
<h3>Stuff</h3>
<p>Stuff.</p>
</div>
</div>
```
Here are the CSS styles for the boxes:
```
/**********************
*******CATEGORIES******
**********************/
.categories {
width: 90%;
margin: 3% 9%;
clear: left;
}
.category {
padding: 7% 5% 3% 5%;
width: 20%;
border: 1px solid #E0E0E0;
float: left;
cursor: pointer;
text-align: center;
}
.category:hover {
border: 1px solid #4F8E64;
}
.category h3 {
color: #3F7250;
margin: 6% 0;
}
.category p {
text-align: center;
}
```
Make sure that the padding and margin and width stays in percentages. Feel free to modify the code and share it with me on fiddle or something. | 2015/10/24 | [
"https://Stackoverflow.com/questions/33316924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5393006/"
]
| Here's a start to see if we're headed in the right direction:
```
>> M = [1 2 3 4;
1 2 8 10;
4 5 7 9;
2 3 6 4;
1 2 4 7];
>> N = M; %// copy M into a new matrix so we can modify it
>> idx = ismember(N(:,1:2), N(1,1:2), 'rows')
idx =
1
1
0
0
1
>> N(idx, :)
ans =
1 2 3 4
1 2 8 10
1 2 4 7
```
Then you can remove those rows from the original matrix and repeat.
```
>> N = N(~idx,:)
N =
4 5 7 9
2 3 6 4
``` | this will give you the results
```
data1 =[1 2 3 4
1 2 8 10
4 5 7 9
2 3 6 4
1 2 4 7];
data2 = [1 2 3 4
1 2 3 10
1 2 4 7];
[exists,position] = ismember(data1,data2, 'rows')
```
where the exists vector tells you wheter the row is on the other matrix and position gives you the position...
a less elegant and simpler version would be
```
array_data1 = reshape (data1',[],1);
array_data2 = reshape (data2',[],1);
matchmatrix = zeros(size(data2,1),size(data1,1));
for irow1 = 1: size(data2,1)
for irow2 = 1: size(data1,1)
matchmatrix(irow1,irow2) = min(data2(irow1,:) == data1(irow2,:))~= 0;
end
end
```
the matchmatrix is to read as a connectivity matrix where value of 1 indicates which row of data1 matches with which row of data2 |
13,134,230 | I have the following column values in my crystal report:
```
|Code |Unit |
|A |2 |
|B |3 |
|C |2 |
|D |3 |
|E |1 |
|F |1 |
|G |4 |
|H |(3) |
```
I want to summarize the Unit except the Units which has Code H,J,K, and L.
The Codes: H,J,K, and L contains units which has parenthesis.
Is there a way to do this? | 2012/10/30 | [
"https://Stackoverflow.com/questions/13134230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925063/"
]
| I use a FSM machine to change the state of the application. Each states shows and hides the appropriate view. My views use transition to animate in and out, so changing the state is more complex, then simple show/hide - it animates in and out from one state into another. I have forked <https://github.com/fschaefer/Stately.js> to fit my needs. | I can share my personal experience with such a problem. I don't know if it's the best solution, but it worked for me.
My problem was even worse because I had several routers and each of them should hide/show views that belong to it. The solution I chose was similar to the first option you consider.
In my router there is an array which holds all existing views. When the state changes and route callback executes all other views are hidden with this simple code `view[i].hide()` and the proper one is shown. You can make View model and Views collection if you would like to have more control.
I think it's a better solution, because when you add a new route, you don't have to add route events to all views. Moreover, your views stay decoupled from the router, they may even don't know it exists. |
72,079,389 | As a new Developer I'd like more information about json file. I know that The this file is the heart of a Node.js system. This file holds the metadata for a particular project. The file is found in the root directory of any Node application or module. Please Write More about it. | 2022/05/01 | [
"https://Stackoverflow.com/questions/72079389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18390083/"
]
| **TLDR:**
`[email protected]` is [incompatible with React 18](https://github.com/Semantic-Org/Semantic-UI-React/issues/4354). As a workaround, you can downgrade your application to **React 17**.
### While resolving: [email protected]
```
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! react@"^18.0.0" from the root project
```
Those first three lines indicate that npm identified **React 18** as your project's dependency.
### Could not resolve dependency
```
npm ERR! peer react@"^16.8.0 || ^17.0.0" from [email protected]
npm ERR! node_modules/semantic-ui-react
npm ERR! semantic-ui-react@"^2.1.2" from the root project
```
These 3 lines list `semantic-ui-react`'s peer dependency, meaning it expects your project to have either **React 16.8** or **React 17** as dependency.
### Fix the upstream dependency conflict
There are two ways to address this conflict:
1. Downgrade your project to **React 17** using `npm install react@17`
2. Override `semantic-ui-react`'s using yarn's [Selective Resolution feature](https://github.com/yarnpkg/yarn/pull/4105). Inside your package.json:
```
"resolutions": {
"semantic-ui-react/react": "^18.0.0"
}
``` | You can use this [article](https://dev.to/lowla/create-react-app-with-a-previous-version-of-react-4g03) it helped me solved the same problem when i wanted to install `semantic-ui` with `react 18` it will probably help you with other frameworks that doesn't compatible with react 18 |
58,376,478 | I'm trying to use a service account to retrieve locations/reviews using the Google My Business API.
So far I have:
1. Created a project in Developers Console
2. Enabled access to the Google My Business API (it's been approved/whitelisted by Google)
3. Created a service account with an associated OAuth identity
4. Invited the OAuth identity (i.e. service account) as a manager for the Google My Business location
I am able to see the invitation when programmatically listing invites from `https://mybusiness.googleapis.com/v4/accounts/[ACCOUNT NAME]/invitations` using Google's sample .NET client available for download from <https://developers.google.com/my-business/samples>
However, when I try to accept the invitation through `https://mybusiness.googleapis.com/v4/accounts/[ACCOUNT NAME]/invitations/[INVITATION NAME]:accept` the request fails with a 500 server error.
When creating the `MyBusinessService` instance, I first create a service account credential like:
```
ServiceAccountCredential credential;
using (Stream stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read, FileShare.Read))
{
credential = (ServiceAccountCredential)GoogleCredential
.FromStream(stream)
.CreateScoped(new [] { "https://www.googleapis.com/auth/plus.business.manage" })
.UnderlyingCredential;
}
```
Next I create an initializer like:
```
var initializer = new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "My GMB API Client",
GZipEnabled = true,
};
```
Finally I create a `MyBusinessService` instance like: `var service = new MyBusinessService(initializer);`
I can list invitations with:
```
service.Accounts
.Invitations
.List("[ACCOUNT NAME]")
.Execute()
.Invitations;
```
However, trying to accept an invitation fails:
```
service.Accounts
.Invitations
.Accept(null, "[INVITATION NAME]")
.Execute();
```
The first parameter is `null` as [this documentation](https://developers.google.com/my-business/reference/rest/v4/accounts.invitations/accept) states that the request body should be empty.
Or is there perhaps some other way to accept the invitation in order to enable the service account to retrieve Google My Business reviews for our location(s)? | 2019/10/14 | [
"https://Stackoverflow.com/questions/58376478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87043/"
]
| To log in as a service account for server to server authentication you need to enable domain wide delegation for your service account. <https://developers.google.com/admin-sdk/directory/v1/guides/delegation>
Once you do this, you can make your service account log into the Google My Business API by impersonating the email address of an approved My Business manager. This is in NodeJS, here is what I used:
```
const { google } = require('googleapis'); // MAKE SURE TO USE GOOGLE API
const { default: axios } = require('axios'); //using this for api calls
const key = require('./serviceaccount.json'); // reference to your service account
const scopes = 'https://www.googleapis.com/auth/business.manage'; // can be an array of scopes
const jwt = new google.auth.JWT({
email: key.client_email,
key: key.private_key,
scopes: scopes,
subject: `[email protected]`
});
async function getAxios() {
const response = await jwt.authorize() // authorize key
let token = response.access_token // dereference token
console.log(response)
await axios.get('https://mybusiness.googleapis.com/v4/accounts', {
headers: {
Authorization: `Bearer ${token}`
} // make request
})
.then((res) => { // handle response
console.log(res.data);
})
.catch((err) => { // handle error
console.log(err.response.data);
})
}
await getAxios(); // call the function
``` | Service accounts in the GMB API can't substitute for a Google user account authentication. You'll need to use Oauth with a user account — for example, a gmail account that has access to the GMB web interface - so that you can perform actions on behalf of a user. |
37,573,802 | Is it possible using Javascript and Html to open a Save As Dialog from a chrome extension on a Windows OS machine?
I have tried the following without luck:
1. The chrome extension's fileBrowserHandler - It works only on Chrome
OS
2. HTML5 input with type= file - It opens the Open dialog but not save
3. Anchor tag with download attribute (Save) - It downloads the file directly
to the browser's download setting. If the browser's setting Ask
Where to save the file is set, it opens the Save dialog. Is there a
way to force the browser setting programatically from the chrome
extension?
Please let me know if there are any other ways to get around this.
Any help would be appreciated.
Thanks! | 2016/06/01 | [
"https://Stackoverflow.com/questions/37573802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6410577/"
]
| To force the Save Dialog from a chrome extension, use chrome extension's download api and set the saveAs options flag to true. Something like this:
```
chrome.downloads.download({
url: window.location.href + '/' + fileName,
filename: fileName,
saveAs: true
}, function (downloadId) {
console.log(downloadId);
});
``` | Try using the [FileSaver](http://purl.eligrey.com/github/FileSaver.js/) HTML5 polyfill. It allows you to save anything to a file from JavaScript:
```js
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");
``` |
105,239 | Creating a character to do an animation but have been very unsuccessful in getting clothes to act like they are on the character. Created him in Make Human. Exported with just s shirt on so I could use that to make his robe/gown. Copied shirt and created gown. Tried many videos and even though none were that similar to mine I tried them all and it partially works when gimbal moves. Anyone else make and rig clothes in similar manner?
[](https://blend-exchange.giantcowfilms.com/b/4719/)
[](https://i.stack.imgur.com/FYyyw.png)
[](https://i.stack.imgur.com/GWAl4.png) | 2018/03/29 | [
"https://blender.stackexchange.com/questions/105239",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/54502/"
]
| Array modifiers will duplicate the uv of the original mesh so any texture you are using on the base mesh will automatically duplicate it over to the array. If you are wanting for each segment to have its own individual texture then you will have to apply the modifier first before you can make adjustments individually. | Once the array has been applied, unwrap using Follow Active Quads and then arrange the resultant UV map (by positioning, rotating, scaling the entire island) so that one ‘face’ is scaled and positioned to fit the whole image. This should result in the image repeating identically for each face. |
56,133,320 | Currently cleaning data from a csv file. Successfully mad everything lowercase, removed stopwords and punctuation etc. But need to remove special characters. For example, the csv file contains things such as 'César' '‘disgrace’'. If there is a way to replace these characters then even better but I am fine with removing them. Below is the code I have so far.
```
import pandas as pd
from nltk.corpus import stopwords
import string
from nltk.stem import WordNetLemmatizer
lemma = WordNetLemmatizer()
pd.read_csv('soccer.csv', encoding='utf-8')
df = pd.read_csv('soccer.csv')
df.columns = ['post_id', 'post_title', 'subreddit']
df['post_title'] = df['post_title'].str.lower().str.replace(r'[^\w\s]+', '').str.split()
stop = stopwords.words('english')
df['post_title'] = df['post_title'].apply(lambda x: [item for item in x if item not in stop])
df['post_title']= df['post_title'].apply(lambda x : [lemma.lemmatize(y) for y in x])
df.to_csv('clean_soccer.csv')
``` | 2019/05/14 | [
"https://Stackoverflow.com/questions/56133320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11496197/"
]
| When saving the file try:
```
df.to_csv('clean_soccer.csv', encoding='utf-8-sig')
```
or simply
```
df.to_csv('clean_soccer.csv', encoding='utf-8')
``` | I'm not sure if there's an easy way to replace the special characters, but I know how you can remove them. Try using:
```
df['post_title']= df['post_title'].str.replace(r'[^A-Za-z0-9]+', '')
```
That should replace 'César' '‘disgrace’' with 'Csardisgrace'. Hope this helps. |
56,133,320 | Currently cleaning data from a csv file. Successfully mad everything lowercase, removed stopwords and punctuation etc. But need to remove special characters. For example, the csv file contains things such as 'César' '‘disgrace’'. If there is a way to replace these characters then even better but I am fine with removing them. Below is the code I have so far.
```
import pandas as pd
from nltk.corpus import stopwords
import string
from nltk.stem import WordNetLemmatizer
lemma = WordNetLemmatizer()
pd.read_csv('soccer.csv', encoding='utf-8')
df = pd.read_csv('soccer.csv')
df.columns = ['post_id', 'post_title', 'subreddit']
df['post_title'] = df['post_title'].str.lower().str.replace(r'[^\w\s]+', '').str.split()
stop = stopwords.words('english')
df['post_title'] = df['post_title'].apply(lambda x: [item for item in x if item not in stop])
df['post_title']= df['post_title'].apply(lambda x : [lemma.lemmatize(y) for y in x])
df.to_csv('clean_soccer.csv')
``` | 2019/05/14 | [
"https://Stackoverflow.com/questions/56133320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11496197/"
]
| When saving the file try:
```
df.to_csv('clean_soccer.csv', encoding='utf-8-sig')
```
or simply
```
df.to_csv('clean_soccer.csv', encoding='utf-8')
``` | As an alternative to other answers, you could use `string.printable`:
```
import string
printable = set(string.printable)
def remove_spec_chars(in_str):
return ''.join([c for c in in_str if c in printable])
df['post_title'].apply(remove_spec_chars)
```
For reference, `string.printable` varies by machine, which is a combination of digits, ascii\_letters, punctuation, and whitespace.
For your example string `César' '‘disgrace’'` this function returns `'Csardisgrace'`.
<https://docs.python.org/3/library/string.html>
[How can I remove non-ASCII characters but leave periods and spaces using Python?](https://stackoverflow.com/questions/8689795/how-can-i-remove-non-ascii-characters-but-leave-periods-and-spaces-using-python) |
21,401,801 | I want to monitor internet in every page in my project through service. I don't have any code regarding this. I have method how to check internet connection, but I want to implement it through service.
1. Is it possible ? if yes please provide me some methods or logic.
Thanks in advance | 2014/01/28 | [
"https://Stackoverflow.com/questions/21401801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064182/"
]
| From the [source](http://www.juliencavandoli.com/how-to-disable-recent-apps-dialog-on-long-press-home-button/)
```
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d("Focus debug", "Focus changed !");
if(!hasFocus) {
Log.d("Focus debug", "Lost focus !");
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
``` | For disable the recent apps button while launching other applications then you can create a service.
public class StatusBarService extends Service {
```
private static final String TAG = StatusBarService.class.getSimpleName();
private volatile boolean isRunning;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
isRunning = true;
// Lock a recentApps button
RecentAppLockerThread thread = new RecentAppLockerThread();
new Thread(thread).start();
}
/**
* Lock a recent apps button
*
*
*/
private class RecentAppLockerThread implements Runnable {
@Override
public void run() {
while (isRunning) {
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
}
@Override
public boolean stopService(Intent name) {
isRunning = false;
return super.stopService(name);
}
@Override
public void onDestroy() {
super.onDestroy();
isRunning = false;
}
```
} |
21,401,801 | I want to monitor internet in every page in my project through service. I don't have any code regarding this. I have method how to check internet connection, but I want to implement it through service.
1. Is it possible ? if yes please provide me some methods or logic.
Thanks in advance | 2014/01/28 | [
"https://Stackoverflow.com/questions/21401801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064182/"
]
| From the [source](http://www.juliencavandoli.com/how-to-disable-recent-apps-dialog-on-long-press-home-button/)
```
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d("Focus debug", "Focus changed !");
if(!hasFocus) {
Log.d("Focus debug", "Lost focus !");
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
``` | ```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d("Focus debug", "Focus changed !");
if(!hasFocus) {
Log.d("Focus debug", "Lost focus !");
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
``` |
21,401,801 | I want to monitor internet in every page in my project through service. I don't have any code regarding this. I have method how to check internet connection, but I want to implement it through service.
1. Is it possible ? if yes please provide me some methods or logic.
Thanks in advance | 2014/01/28 | [
"https://Stackoverflow.com/questions/21401801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064182/"
]
| For disabling Recent button add this code to your Main activity:
```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!hasFocus) {
windowCloseHandler.post(windowCloserRunnable);
}
}
private void toggleRecents() {
Intent closeRecents = new Intent("com.android.systemui.recent.action.TOGGLE_RECENTS");
closeRecents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
ComponentName recents = new ComponentName("com.android.systemui", "com.android.systemui.recent.RecentsActivity");
closeRecents.setComponent(recents);
this.startActivity(closeRecents);
}
private Handler windowCloseHandler = new Handler();
private Runnable windowCloserRunnable = new Runnable() {@Override public void run() {
ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
if (cn != null && cn.getClassName().equals("com.android.systemui.recent.RecentsActivity")) {
toggleRecents();
}
}
};
``` | For disable the recent apps button while launching other applications then you can create a service.
public class StatusBarService extends Service {
```
private static final String TAG = StatusBarService.class.getSimpleName();
private volatile boolean isRunning;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
isRunning = true;
// Lock a recentApps button
RecentAppLockerThread thread = new RecentAppLockerThread();
new Thread(thread).start();
}
/**
* Lock a recent apps button
*
*
*/
private class RecentAppLockerThread implements Runnable {
@Override
public void run() {
while (isRunning) {
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
}
@Override
public boolean stopService(Intent name) {
isRunning = false;
return super.stopService(name);
}
@Override
public void onDestroy() {
super.onDestroy();
isRunning = false;
}
```
} |
21,401,801 | I want to monitor internet in every page in my project through service. I don't have any code regarding this. I have method how to check internet connection, but I want to implement it through service.
1. Is it possible ? if yes please provide me some methods or logic.
Thanks in advance | 2014/01/28 | [
"https://Stackoverflow.com/questions/21401801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064182/"
]
| ```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d("Focus debug", "Focus changed !");
if(!hasFocus) {
Log.d("Focus debug", "Lost focus !");
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
``` | For disable the recent apps button while launching other applications then you can create a service.
public class StatusBarService extends Service {
```
private static final String TAG = StatusBarService.class.getSimpleName();
private volatile boolean isRunning;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
isRunning = true;
// Lock a recentApps button
RecentAppLockerThread thread = new RecentAppLockerThread();
new Thread(thread).start();
}
/**
* Lock a recent apps button
*
*
*/
private class RecentAppLockerThread implements Runnable {
@Override
public void run() {
while (isRunning) {
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
}
@Override
public boolean stopService(Intent name) {
isRunning = false;
return super.stopService(name);
}
@Override
public void onDestroy() {
super.onDestroy();
isRunning = false;
}
```
} |
21,401,801 | I want to monitor internet in every page in my project through service. I don't have any code regarding this. I have method how to check internet connection, but I want to implement it through service.
1. Is it possible ? if yes please provide me some methods or logic.
Thanks in advance | 2014/01/28 | [
"https://Stackoverflow.com/questions/21401801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064182/"
]
| For disabling Recent button add this code to your Main activity:
```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!hasFocus) {
windowCloseHandler.post(windowCloserRunnable);
}
}
private void toggleRecents() {
Intent closeRecents = new Intent("com.android.systemui.recent.action.TOGGLE_RECENTS");
closeRecents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
ComponentName recents = new ComponentName("com.android.systemui", "com.android.systemui.recent.RecentsActivity");
closeRecents.setComponent(recents);
this.startActivity(closeRecents);
}
private Handler windowCloseHandler = new Handler();
private Runnable windowCloserRunnable = new Runnable() {@Override public void run() {
ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
if (cn != null && cn.getClassName().equals("com.android.systemui.recent.RecentsActivity")) {
toggleRecents();
}
}
};
``` | ```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d("Focus debug", "Focus changed !");
if(!hasFocus) {
Log.d("Focus debug", "Lost focus !");
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
``` |
39,237,237 | I have multiples views but the same search input on a navbar, the question is: **How use the input in the navbar to update data in view1Ctrl , View2Ctrl or anyCtrl**
**------- EDIT 1 -------**
My question was not specific
**I want to use the input in the navbar to update data in view1Ctrl , View2Ctrl or anyCtrl and how the controller knows if the serch input is used?**
In the real code i have a service that calls a $http get function and uptate the and on success update the array
```
$scope.loadMore = function() {
$scope.busy = true
data.all(page)
.then(function success (response) {
var data = response.data
for(var i = 0; i < data.length; i++) {
$scope.array1.push(data[i])
}
page++
$scope.busy = false
})
}
$scope.searchData = function (search) {
$scope.busy = true
$scope.array1 = [];
data.all(page, search)
.then(function success (response) {
var data = response.data
for(var i = 0; i < data.length; i++) {
$scope.array1.push(data[i])
}
page++
$scope.busy = false
})
}
```
I create a plnkr to clarify any doubts.
<https://plnkr.co/edit/tENpWjPAzbV0GBg52L1V?p=preview>
Thanks for help!
App.js
```js
var app = angular.module('plunker', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider
.otherwise("/home/view1");
$stateProvider
.state('home', {
url: "/home",
templateUrl: "./home-main.html",
})
.state('home.view1', {
url: "/view1",
templateUrl: "./view1.html",
controller: "view1Ctrl"
})
.state('home.view2', {
url: "/view2",
templateUrl: "./view2.html",
controller: "view2Ctrl"
})
})
app.directive('navbar', function() {
return {
restrict: 'EA',
templateUrl: './navbar.html',
controller: 'view1Ctrl'
}
})
app.controller('view1Ctrl', function($scope) {
$scope.array1 = [1, 2, 3, 4];
$scope.search = ''
$scope.onSearch = function() {
console.log('calling onSearch')
$scope.array1 = [1.1, 1.2, 1.3, 1.4]
}
});
app.controller('view2Ctrl', function($scope) {
$scope.array1 = [1, 2, 3, 4];
$scope.search = ''
$scope.onSearch = function() {
console.log('calling onSearch')
$scope.array1 = [1.1, 1.2, 1.3, 1.4]
}
});
``` | 2016/08/30 | [
"https://Stackoverflow.com/questions/39237237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5111445/"
]
| Maybe I do not understand this correctly, but there's no need to check for *existance*. You can alter a table's column to `NOT NULL` over and over again - if you like.
Try this:
```
CREATE TABLE Test(ID INT,SomeValue VARCHAR(100));
INSERT INTO Test VALUES(1,NULL),(2,'Value 2'),(NULL,'Value NULL');
```
--Ups, ID should not be NULL, but this throws an error
```
--ALTER TABLE Test ALTER COLUMN ID INT NOT NULL;
```
--First have to correct the missing value
```
UPDATE Test SET ID=3 WHERE SomeValue='Value NULL';
```
--Now this works
```
ALTER TABLE Test ALTER COLUMN ID INT NOT NULL;
```
--No problem to put this statement again. No need to check for existance...
```
ALTER TABLE Test ALTER COLUMN ID INT NOT NULL;
```
--Clean-Up
```
GO
DROP TABLE Test;
``` | You can use views in `sys` namespace for this purpose. Something like this.
```
select c.name,t.name,c.is_nullable
from sys.all_columns c
inner join sys.tables t on c.object_id=t.object_id
where t.name = 'MyTable' and c.name = 'myCol';
```
and then `alter table ... alter column...` |
57,959,682 | At my work I manually copy sales forecast into another file that gets uploaded to our website.
The two files I manually copy have the same exact layout everytime (no cells are changing positions) but the name of the file changes due to having different products every day.
I tried the VBA record button but since the file changes its name everyday then it becomes useless, since it would require me to change the name of the file in every sentence.
Can I somehow define the name of the file in the beginning so I only have to change that when I run the macro?
```
Sub Test2()
' Test2 Macro
Dim FileName As String
FileName = ""
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "Select File"
.Filters.Add "Excel File", "*.xls?"
.AllowMultiSelect = False
If .Show Then
FileName = .SelectedItems(1)
End If
End With
If Len(FileName) < 4 Then Exit Sub 'No file selected
Dim TempWorkbook As Workbook
Set TempWorkbook = Workbooks.Open(FileName, ReadOnly:=True)
ActiveSheet.Range("U8").FormulaR1C1 = "=" & TempWorkbook.Worksheets("FINAL FORM").Cells(18, 2).Address(True, True, xlR1C1, True)
TempWorkbook.Close SaveChanges:=False
Set TempWorkbook = Nothing
End Sub
```
For example somehow define [MNY FDL CS Lifter Lip.xlsx] to "wb1" and then have that in the following sentences so I only have to change the name in the define sentence? | 2019/09/16 | [
"https://Stackoverflow.com/questions/57959682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12074970/"
]
| I would suggest skipping the Interop and using the nuget package: [ExcelDataReader](https://github.com/ExcelDataReader/). It does not require excel on the running machine and also works in Linux builds of Core applications.
The library does support password protected excel files. | There is not much that you can collect from Excel workbook using interop APIs, but what you can collect is file name etc. Check out the sample code below.
```
var xls = new Excel.Application();
var activeProtectedViewWindow =
xls?.ActiveProtectedViewWindow;
var spath = activeProtectedViewWindow.SourcePath;
var sfname = activeProtectedViewWindow.SourceName;
``` |
1,471,437 | When i implement
```
WaitCallback waitCB = new WaitCallback(DisplayTime);
for (int i = 1; i <= 5; i++)
{
ThreadPool.QueueUserWorkItem(waitCB, null);
Thread.Sleep(2000);
}
public void DisplayTime(object state)
{
Console.WriteLine("Current Time {0} ", DateTime.Now);
}
```
( 1 ) Does it mean ,my job is queued into to CLR ?
( 2 ) Will CLR process it after finishing the existing pending item in the queue ?
( 3 ) Will the time to process my item in the queue is not predictable? | 2009/09/24 | [
"https://Stackoverflow.com/questions/1471437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160677/"
]
| >
> ( 1 ) Does it mean ,my job is queued into to CLR ?
>
>
>
It is queued to be processed as soon as a thread from the pool is available
>
> ( 2 ) Will CLR process it after finishing the existing pending item in the queue ?
>
>
>
There can be several jobs executing at the same time... As soon as one of the pool threads is available, it is used to process the next item from the queue
>
> ( 3 ) Will the time to process my item in the queue is not predictable?
>
>
>
No, at least not easily... you would have to know how long the queued jobs take to execute, and keep track of each job to calculate the execution time of a given job. Why would you want to know that anyway ? | Your callback will be executed on a threadpool thread based on whatever algorithm the CLR is using to allocate and start threads from its pool.
In your example the callbacks will be processed close to instantly and in a seemingly deterministic fashion. However that could easily change depending on the state of the threadpool. If your process had used up all the threads in the pool then your callback would not get executed until a thread somewhere else completed and was available to it. |
33,596,372 | ```
NSKeyedArchiver.archiveRootObject(<#rootObject: AnyObject#>, toFile: <#String#>)
```
Only returns true the first time. Every next time I call it, the method returns false.
I read some SO, some posts said that I can't rewrite data this way. However, I tried :
```
NSFileManager.defaultManager().removeItemAtPath(path, error: nil)
```
and it still didn't help.
What I did:
1. Checked all my model files for the `NSCoding` protocol
2. Checked all my `required init(coder aDecoder: NSCoder)` and `func encodeWithCoder(aCoder: NSCoder)`
I am missing something, since I have done this in my last app and it worked fla`
```
import Foundation
private let ON_DISK_DATA_DICTIONARY = "savedDataPathsOnDisk"
private let _WBMAccessDataOnDiskMShared = WBMAccessDataOnDiskM()
private var dataDirectories:NSArray! = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
private var dataDirectoryURL:NSURL! = NSURL(fileURLWithPath: dataDirectories.objectAtIndex(0) as! String, isDirectory: true)
private var dataDirectoryPath:String! = dataDirectoryURL.path!
let FILE_FORMAT = ".archive"
class WBMAccessDataOnDiskM: NSObject
{
class var sharedData: WBMAccessDataOnDiskM
{
return _WBMAccessDataOnDiskMShared
}
private var dataAndPathDictionary = [String:String]()
func getDataAndPathDictionary() -> [String:String]
{
return self.dataAndPathDictionary
}
func addDataAndPathToDictionary(data:String ,path:String)
{
if !checkIfDataAllreadyExists(data)
{
let fullPath = createFullDataPath(path)
dataAndPathDictionary[data] = fullPath
NSUserDefaults.standardUserDefaults().setObject(dataAndPathDictionary, forKey: ON_DISK_DATA_DICTIONARY)
}
}
func checkIfDataIsAvailable(dataPathComponent:String) -> (Bool,String)
{
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
var dataPath = paths.stringByAppendingPathComponent(dataPathComponent)
var checkValidation = NSFileManager.defaultManager()
println(dataPathComponent)
if (checkValidation.fileExistsAtPath(dataPath))
{
return (true,dataPath)
}
else
{
return (false,"")
}
}
func checkForDataOnDisk() -> Bool
{
let dataDict = NSUserDefaults.standardUserDefaults().objectForKey(ON_DISK_DATA_DICTIONARY) as? [String:String]
if dataDict == nil
{
return false
}
else
{
dataAndPathDictionary = dataDict!
return true
}
}
private func checkIfDataAllreadyExists(data:String) -> Bool
{
let keys = self.dataAndPathDictionary.keys.array
if contains(keys, data)
{
return true
}
return false
}
private func createFullDataPath(path:String) -> String
{
var fullPathURL = dataDirectoryURL.URLByAppendingPathComponent(path + FILE_FORMAT)
return fullPathURL.path!
}
func saveDataArray(data:[AnyObject], path:String)
{
NSFileManager.defaultManager().removeItemAtPath(path, error: nil)
if NSKeyedArchiver.archiveRootObject(data, toFile: path)
{
// SAVING
println(" Saving data ARRAY ")
}
else
{
println(" NOT saving data ARRAY ")
}
}
func saveDataObject(dataObject:AnyObject, path:String)
{
if NSKeyedArchiver.archiveRootObject(dataObject, toFile: path)
{
println(" Saving data OBJECT ")
}
else
{
println(" NOT saving data OBJECT ")
}
}
// dataFromDisk = NSKeyedUnarchiver.unarchiveObjectWithFile(pathForNews) as? [AnyObject]
func loadDataArray(path:String) -> [AnyObject]?
{
var dataArrayFromDisk: [AnyObject]?
dataArrayFromDisk = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? [AnyObject]
return dataArrayFromDisk
}
func loadDataObject(path:String) -> AnyObject?
{
var dataObjectFromDisk: AnyObject?
dataObjectFromDisk = NSKeyedUnarchiver.unarchiveObjectWithFile(path)
return dataObjectFromDisk
}
func getNewsDataLanguagePath() -> String
{
var currentOSLanguage = LOCALIZATION.currentOsLanguage
currentOSLanguage = currentOSLanguage.substringToIndex(2)
if currentOSLanguage == "de"
{
return ON_DISK_CONTENT_DE
}
else if currentOSLanguage == "en"
{
return ON_DISK_CONTENT_ENG
}
return ON_DISK_CONTENT_ENG
}
`
```
I am using Xcode 6.4 and Swift 1.2.
Any help & code correction is welcome. | 2015/11/08 | [
"https://Stackoverflow.com/questions/33596372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3009276/"
]
| Because of the code you put here does't contain the call of `saveDataArray` or `saveDataObject` so I judge that you have maintain the path of a archived object manually.**This is where thing went wrong.** The method of NSKeyedArchiver named `archiveRootObject` can automatically maintain the archiver file path.
In the Apple's doucumet
>
> Archives an object graph rooted at a given object by encoding it into a data object then atomically writes the resulting data object to a file at a given path, and returns a Boolean value that indicates whether the operation was successful.
>
>
>
And there is another question in [SO](https://stackoverflow.com/a/14326696/4383896) may help you. | I followed apple instructions in this good example: [Persist Data](https://developer.apple.com/library/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson10.html)
But I had the same problem you describe with my app for AppleTV. At the end I change .Documents directory for CacheDirectory and it's working well.
```
static let DocumentsDirectorio = NSFileManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first!
``` |
32,905,860 | I need to create a set of matrices from the file below, the lines/rows with the same value of Z will go in a matrix together.
Below is a shortened version of my txt file:
```
X Y Z
-1 10 0
1 20 5
2 15 10
2 50 10
2 90 10
3 15 11
4 50 11
5 90 11
6 13 14
7 50 14
8 70 14
8 95 14
8 75 14
```
So for example my first matrix will be
```
[-1, 10, 0],
```
my second one will be
```
[1, 20, 5],
```
my third will be
```
([2, 15, 10],
[2, 50, 10],
[2, 90, 10]) etc
```
I've looked at a few questions related to this but nothing seems to be quite right.
I started by making each column an array. I was thinking a for loop might work well. So far I have
```
f = open("data.txt", "r")
header1 = f.readline()
for line in f:
line = line.strip()
columns = line.split()
x = columns[0]
y = columns[1]
z = columns[2]
i = line in f
z.old = line(i-1,4)
i=1
for line in f:
f.readline(i)
if z(0) == [i,3]:
line(i) = matrix[i,:]
else z(0) != [i,3]:
store line(i) as M
continue
i = i+1
```
however, I'm getting 'invalid syntax' for line,
```
else z(0) != line(4):
```
By this else clause, I mean that `if z(0)/(z initial) is not equal to line(4)` then this line will then get stored as the first line of the next matrix we will check under this code.
However, I'm not sure how well this would work.
Any help would be greatly appreciated! | 2015/10/02 | [
"https://Stackoverflow.com/questions/32905860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5371327/"
]
| Try to edit your template
-------------------------
**Go to File->Settings->Editors->File and Code Templates**
here find your unit test template and modify it as you wish
[](https://i.stack.imgur.com/NGgH6.png)
Once you have modified it all you future test would be with modifications | Unless you object to using wildcard imports, `static import org.junit.Assert.*;` will sort you out nicely.
The recommendation is to use static imports sparingly (and wildcards even more so), but unit testing is one place where that becomes quite common and is somewhat risk-free. |
26,361,797 | Every time an user click on the button it has to show "John - Sue" or "Sue - John".
I tried with this code:
```
public class MyActivity extends Activity {
ArrayList<String> names = new ArrayList<String>();
int p1, p2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
names.add("John");
names.add("Sue");
Button b = (Button) findViewById(R.id.mybutton);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
p1 = (int)Math.random();
if (p1 == 0)
p2 = 1;
else
p2 = 0;
String msg = names.get(p1) + " - " + names.get(p2);
AlertDialog msgbox = new AlertDialog.Builder(About.this).setTitle("Click here").setMessage(msg).create();
//msgbox.setPositiveButton("OK", null);
msgbox.setCancelable(true);
msgbox.show();
TextView textView = (TextView) msgbox.findViewById(android.R.id.message);
textView.setTextSize(16);
}
});
}
}
```
But i get always the same order, even i close and run again the app. How to do that? | 2014/10/14 | [
"https://Stackoverflow.com/questions/26361797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2516399/"
]
| If you want shuffle list:
```
Collections.shuffle(names)
```
If you want random int between 0 or 1 ([nextInt(int) javadoc](http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int))):
```
Random random = new Random();
int randomInt = random.nextInt(2);
``` | Math.random() returns a number between 0 and 1. So when you cast it to int it will always be 0.
Try this:
```
p1 = (int)(Math.random()*2);
``` |
26,361,797 | Every time an user click on the button it has to show "John - Sue" or "Sue - John".
I tried with this code:
```
public class MyActivity extends Activity {
ArrayList<String> names = new ArrayList<String>();
int p1, p2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
names.add("John");
names.add("Sue");
Button b = (Button) findViewById(R.id.mybutton);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
p1 = (int)Math.random();
if (p1 == 0)
p2 = 1;
else
p2 = 0;
String msg = names.get(p1) + " - " + names.get(p2);
AlertDialog msgbox = new AlertDialog.Builder(About.this).setTitle("Click here").setMessage(msg).create();
//msgbox.setPositiveButton("OK", null);
msgbox.setCancelable(true);
msgbox.show();
TextView textView = (TextView) msgbox.findViewById(android.R.id.message);
textView.setTextSize(16);
}
});
}
}
```
But i get always the same order, even i close and run again the app. How to do that? | 2014/10/14 | [
"https://Stackoverflow.com/questions/26361797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2516399/"
]
| If you want shuffle list:
```
Collections.shuffle(names)
```
If you want random int between 0 or 1 ([nextInt(int) javadoc](http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int))):
```
Random random = new Random();
int randomInt = random.nextInt(2);
``` | It happens because
`p1 = (int)Math.random();`
always gives you zero. |
70,293,840 | I am trying to send Emails through Gmail but exception "**Unknown SMTP host: smtp.gmail.com**".
I already **Turned on** Less secure app access and Two Step Verification should be **turned off**.
```
public class MonitoringMail
{
public void sendMail(String mailServer, String from, String[] to, String subject, String messageBody) throws MessagingException, AddressException
{
boolean debug = false;
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.EnableSSL.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", mailServer);
props.put("mail.debug", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
try
{
Transport bus = session.getTransport("smtp");
bus.connect();
Message message = new MimeMessage(session);
//X-Priority values are generally numbers like 1 (for highest priority), 3 (normal) and 5 (lowest).
message.addHeader("X-Priority", "1");
message.setFrom(new InternetAddress(from));
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++)
addressTo[i] = new InternetAddress(to[i]);
message.setRecipients(Message.RecipientType .TO, addressTo);
message.setSubject(subject);
BodyPart body = new MimeBodyPart();
// body.setText(messageBody);
body.setContent(messageBody,"text/html");
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
// multipart.addBodyPart(attachment);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sucessfully Sent mail to All Users");
bus.close();
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
```
It's working earlier but one week later I got an exception.
I try to resolve this exception and I spent 3 days but I cant resolve these issues please try to resolve this. | 2021/12/09 | [
"https://Stackoverflow.com/questions/70293840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12569370/"
]
| SMTP have 2 different ports
PORTS for **SSL** 465
PORTS for **TLS/STARTTLS** 587
did you try with another ports ? | Please try with port 25.
```
props.setProperty("mail.smtp.port", "25");
``` |
70,293,840 | I am trying to send Emails through Gmail but exception "**Unknown SMTP host: smtp.gmail.com**".
I already **Turned on** Less secure app access and Two Step Verification should be **turned off**.
```
public class MonitoringMail
{
public void sendMail(String mailServer, String from, String[] to, String subject, String messageBody) throws MessagingException, AddressException
{
boolean debug = false;
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.EnableSSL.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", mailServer);
props.put("mail.debug", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
try
{
Transport bus = session.getTransport("smtp");
bus.connect();
Message message = new MimeMessage(session);
//X-Priority values are generally numbers like 1 (for highest priority), 3 (normal) and 5 (lowest).
message.addHeader("X-Priority", "1");
message.setFrom(new InternetAddress(from));
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++)
addressTo[i] = new InternetAddress(to[i]);
message.setRecipients(Message.RecipientType .TO, addressTo);
message.setSubject(subject);
BodyPart body = new MimeBodyPart();
// body.setText(messageBody);
body.setContent(messageBody,"text/html");
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
// multipart.addBodyPart(attachment);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sucessfully Sent mail to All Users");
bus.close();
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
```
It's working earlier but one week later I got an exception.
I try to resolve this exception and I spent 3 days but I cant resolve these issues please try to resolve this. | 2021/12/09 | [
"https://Stackoverflow.com/questions/70293840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12569370/"
]
| SMTP have 2 different ports
PORTS for **SSL** 465
PORTS for **TLS/STARTTLS** 587
did you try with another ports ? | I understand that you've setup gmail account and enabled less secured apps, but Gmail account automatically turns off "allow less secured apps" option after some period of inactivity. If this code worked before, try to check your gmail account settings again. |
70,293,840 | I am trying to send Emails through Gmail but exception "**Unknown SMTP host: smtp.gmail.com**".
I already **Turned on** Less secure app access and Two Step Verification should be **turned off**.
```
public class MonitoringMail
{
public void sendMail(String mailServer, String from, String[] to, String subject, String messageBody) throws MessagingException, AddressException
{
boolean debug = false;
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.EnableSSL.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", mailServer);
props.put("mail.debug", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
try
{
Transport bus = session.getTransport("smtp");
bus.connect();
Message message = new MimeMessage(session);
//X-Priority values are generally numbers like 1 (for highest priority), 3 (normal) and 5 (lowest).
message.addHeader("X-Priority", "1");
message.setFrom(new InternetAddress(from));
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++)
addressTo[i] = new InternetAddress(to[i]);
message.setRecipients(Message.RecipientType .TO, addressTo);
message.setSubject(subject);
BodyPart body = new MimeBodyPart();
// body.setText(messageBody);
body.setContent(messageBody,"text/html");
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
// multipart.addBodyPart(attachment);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sucessfully Sent mail to All Users");
bus.close();
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
```
It's working earlier but one week later I got an exception.
I try to resolve this exception and I spent 3 days but I cant resolve these issues please try to resolve this. | 2021/12/09 | [
"https://Stackoverflow.com/questions/70293840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12569370/"
]
| SMTP have 2 different ports
PORTS for **SSL** 465
PORTS for **TLS/STARTTLS** 587
did you try with another ports ? | In my case i was change ports after that it's working properly |
70,293,840 | I am trying to send Emails through Gmail but exception "**Unknown SMTP host: smtp.gmail.com**".
I already **Turned on** Less secure app access and Two Step Verification should be **turned off**.
```
public class MonitoringMail
{
public void sendMail(String mailServer, String from, String[] to, String subject, String messageBody) throws MessagingException, AddressException
{
boolean debug = false;
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.EnableSSL.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", mailServer);
props.put("mail.debug", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
try
{
Transport bus = session.getTransport("smtp");
bus.connect();
Message message = new MimeMessage(session);
//X-Priority values are generally numbers like 1 (for highest priority), 3 (normal) and 5 (lowest).
message.addHeader("X-Priority", "1");
message.setFrom(new InternetAddress(from));
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++)
addressTo[i] = new InternetAddress(to[i]);
message.setRecipients(Message.RecipientType .TO, addressTo);
message.setSubject(subject);
BodyPart body = new MimeBodyPart();
// body.setText(messageBody);
body.setContent(messageBody,"text/html");
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
// multipart.addBodyPart(attachment);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sucessfully Sent mail to All Users");
bus.close();
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
```
It's working earlier but one week later I got an exception.
I try to resolve this exception and I spent 3 days but I cant resolve these issues please try to resolve this. | 2021/12/09 | [
"https://Stackoverflow.com/questions/70293840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12569370/"
]
| Please try with port 25.
```
props.setProperty("mail.smtp.port", "25");
``` | In my case i was change ports after that it's working properly |
70,293,840 | I am trying to send Emails through Gmail but exception "**Unknown SMTP host: smtp.gmail.com**".
I already **Turned on** Less secure app access and Two Step Verification should be **turned off**.
```
public class MonitoringMail
{
public void sendMail(String mailServer, String from, String[] to, String subject, String messageBody) throws MessagingException, AddressException
{
boolean debug = false;
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.EnableSSL.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", mailServer);
props.put("mail.debug", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
try
{
Transport bus = session.getTransport("smtp");
bus.connect();
Message message = new MimeMessage(session);
//X-Priority values are generally numbers like 1 (for highest priority), 3 (normal) and 5 (lowest).
message.addHeader("X-Priority", "1");
message.setFrom(new InternetAddress(from));
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++)
addressTo[i] = new InternetAddress(to[i]);
message.setRecipients(Message.RecipientType .TO, addressTo);
message.setSubject(subject);
BodyPart body = new MimeBodyPart();
// body.setText(messageBody);
body.setContent(messageBody,"text/html");
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
// multipart.addBodyPart(attachment);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sucessfully Sent mail to All Users");
bus.close();
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
```
It's working earlier but one week later I got an exception.
I try to resolve this exception and I spent 3 days but I cant resolve these issues please try to resolve this. | 2021/12/09 | [
"https://Stackoverflow.com/questions/70293840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12569370/"
]
| I understand that you've setup gmail account and enabled less secured apps, but Gmail account automatically turns off "allow less secured apps" option after some period of inactivity. If this code worked before, try to check your gmail account settings again. | In my case i was change ports after that it's working properly |
23,154,829 | It seems when I use Postal to send an email using Layout, the headers was not parsed and included on the mail message.
**Views/Emails/\_ViewStart.cshtml**
```
@{ Layout = "~/Views/Emails/_EmailLayout.cshtml"; }
```
**Views/Emails/\_EmailLayout.cshtml**
```
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ViewEmails</title>
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>
```
**Views/Emails/ResetPassword.cshtml**
```
To: @ViewBag.To
From: @ViewBag.From
Subject: Reset Password
Views: Html
```
**Views/Emails/ResetPassword.html.cshtml**
```
Content-Type: text/html; charset=utf-8
Here is your link, etc ...
```
When i received the mail all the headers To, From, Subject and Views are included in the body.
Anyone know how to do it correctly ?
**UPDATED (Thanks to Andrew), this works :**
**Views/Emails/\_EmailLayout.cshtml**
```
@RenderSection("Headers", false)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ViewEmails</title>
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>
```
**Views/Emails/ResetPassword.cshtml**
```
@section Headers {
To: @ViewBag.To
From: @ViewBag.From
Subject: Reset Password
Views: Html
}
```
**Views/Emails/ResetPassword.html.cshtml**
```
@section Headers {
Content-Type: text/html; charset=utf-8
}
Here is your link, etc ...
``` | 2014/04/18 | [
"https://Stackoverflow.com/questions/23154829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/671714/"
]
| One option is to use a Razor section.
At the top of the layout add:
```
@RenderSection("Headers")
```
Then in the view add:
```
@section Headers {
To: @ViewBag.To
From: @ViewBag.From
Subject: Reset Password
Views: Html
}
``` | Move the first line
Content-Type: text/html; charset=utf-8
from Views/Emails/ResetPassword.html.cshtml to Views/Emails/\_EmailLayout.cshtml
```
Content-Type: text/html; charset=utf-8
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ViewEmails</title>
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>
``` |
60,308,981 | My app is unable to detect the state change that occurs when a user logs in without completely refreshing the page. Upon refreshing everything displays correctly. I am using Nuxt and its included auth module documented here - <https://auth.nuxtjs.org/>.
Here is the v-if statement that is unable to detect the state change:
```
<template v-if="$auth.$state.loggedIn">
<nuxt-link
to="/profile"
>
Hello, {{ $auth.$state.user.name }}
</nuxt-link>
</template>
<template v-else>
<nuxt-link
to="/logIn"
>
Sign In
</nuxt-link>
</template>
```
Here is the login method in my login page.
```
methods: {
async onLogin() {
try{
this.$auth.loginWith("local", {
data: {
email: this.email,
password: this.password
}
});
this.$router.push("/");
}catch(err){
console.log(err);
}
}
}
```
I tried fetching the state via a computed property but got the same result. I can see the vuex store data change to indicate I am correctly logged in/out in the 'Application' tab in Chrome Dev Tools but the Vue Dev seems to constantly indicate I'm logged in.. Not sure if its just buggy though..
I also encounter the same problem in reverse when logging out. Here's the method:
```
async onLogout() {
try{
await this.$auth.logout();
}catch(err){
console.log(err);
}
}
```
I am happy to provide further details. | 2020/02/19 | [
"https://Stackoverflow.com/questions/60308981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4266752/"
]
| 1. In `store/index.js` add this :
```
export const getters = {
isAuthenticated(state) {
return state.auth.loggedIn
},
loggedInUser(state) {
return state.auth.user
},
};
```
2. In the pages you are suppose to be authenticated
* use middle ware auth as : `middleware: 'auth'`
* use `import { mapGetters } from 'vuex'`
* in computed add `...mapGetters(['isAuthenticated', 'loggedInUser']),`
3. you can use loggedInUser to get your user details or check if isAuthenticated
and the logout would work as expected as long as your are importing the map getters in the computed | Sometimes Vue's reactivity system falls short and you just need to manually trigger a re-render and the simplest way to do so is by wrapping your function logic in `setTimeout()`
```js
setTimeout(async () => {
await this.$auth.logout();
}, 0);
``` |
52,742,585 | why does my app crash when i click the button to go to the next page?
On the 1st page `onCreate` method
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startBtn = findViewById(R.id.startBtn);
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent ready = new Intent(view.getContext(), ready.class);
// ready.putExtra(name, 1);
// startActivityForResult(ready, 1);
startActivity(ready);
}
});
}
```
On the 2nd page `onCreate` method
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ready);
}
```
the app goes straight into a loop and then crashes.
log:
>
> at android.app.Activity.startActivity(Activity.java:4883)
> at android.app.Activity.startActivity(Activity.java:4851)
> at com.example.ng\_we.capsize.MainActivity$1.onClick(MainActivity.java:32)
> at android.view.View.performClick(View.java:6877)
> at android.widget.TextView.performClick(TextView.java:12651)
> at android.view.View$PerformClick.run(View.java:26069)
>
>
>
it just says the error is at startActivity();
code for button xml:
```
<Button
android:id="@+id/startBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start"
android:textSize="35dp"
android:background="@android:color/holo_green_light"
android:textStyle="bold"/>
```
this is the code for ready.xml, its simple... i dont think its the cause
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginLeft="10px">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="3"
android:layout_marginTop="250px"
android:text="Welcome"
android:textColor="@android:color/black"
android:textSize="25dp"/>
<TextView
android:id="@+id/startName"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="7"
android:layout_marginTop="250px"
android:textSize="25dp"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="40dp"
android:text="ARE YOU READY?"
android:fontFamily="sans-serif-condensed"
android:textAlignment="center"
android:layout_marginTop="100px"
android:textColor="@android:color/holo_red_dark"/>
<Button
android:id="@+id/readyBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ready"
android:textSize="50dp"
android:layout_marginTop="100px"
android:layout_marginLeft="10px"
android:layout_marginRight="10px"
android:background="@android:color/holo_green_dark"
android:fontFamily="sans-serif"
android:textStyle="bold"/>
</LinearLayout>
``` | 2018/10/10 | [
"https://Stackoverflow.com/questions/52742585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7515191/"
]
| I forgot to add in the 2nd page to the manifest file... | ```
this is my Button code :
<Button
android:id="@+id/startBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
//-------------------------this is click listener of button-------------
Button startBtn = findViewById(R.id.startBtn);
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent ready = new Intent(MainActivity.this, ready.class);
startActivity(ready);
}
});
``` |
5,677,446 | I have two independently running scripts.
first one lets say script A calculates some values. And i want to echo these values from other script called B. These scripts will not call each other. I have used export keyword but didn't work. How can i do this? | 2011/04/15 | [
"https://Stackoverflow.com/questions/5677446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/663229/"
]
| If I understood the requirement then can't both scripts be simply executed in same sub shell, independently but **without** calling each other or without any need of an external file or pipe like this:
Let's say this is your **script1.sh**
```
#!/bin/bash
# script1.sh: do something and finally
export x=19
```
And here us your **script2.sh**
```
#!/bin/bash
# script2.sh: read value of $x here
echo "x="${x}
```
Just call them in same sub-shell like this
```
(. ./script1.sh && ./script2.sh)
```
**OUTPUT:**
```
x=19
``` | You may echo values to files, then the other script may read them. If you want to use it as a parameter for something, use reverse aposthrophe:
```
echo `cat storedvalue`
```
Be careful, if the two scripts are running at the same time, concurrency problems may occur, which can cause rarely appearing, mystic-looking errors. |
5,677,446 | I have two independently running scripts.
first one lets say script A calculates some values. And i want to echo these values from other script called B. These scripts will not call each other. I have used export keyword but didn't work. How can i do this? | 2011/04/15 | [
"https://Stackoverflow.com/questions/5677446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/663229/"
]
| If I understood the requirement then can't both scripts be simply executed in same sub shell, independently but **without** calling each other or without any need of an external file or pipe like this:
Let's say this is your **script1.sh**
```
#!/bin/bash
# script1.sh: do something and finally
export x=19
```
And here us your **script2.sh**
```
#!/bin/bash
# script2.sh: read value of $x here
echo "x="${x}
```
Just call them in same sub-shell like this
```
(. ./script1.sh && ./script2.sh)
```
**OUTPUT:**
```
x=19
``` | Can't you read a third file, let's say settings.sh with the common exported variables?
```
# common.sh
export MY_PATH=/home/foo/bar/
export VERSION=42.2a
```
and in both A and B `source common.sh` to load those values.
Note that the export may not be required in that case. |
5,677,446 | I have two independently running scripts.
first one lets say script A calculates some values. And i want to echo these values from other script called B. These scripts will not call each other. I have used export keyword but didn't work. How can i do this? | 2011/04/15 | [
"https://Stackoverflow.com/questions/5677446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/663229/"
]
| ```
mkfifo /tmp/channel
process_a.sh > /tmp/channel&
process_b.sh < /tmp/channel&
wait
```
Of course you can also just read a single line when you want it.
In bash there are coprocs, which also might be what you want. Random example from [this page](http://wiki.bash-hackers.org/syntax/keywords/coproc)
```
# let the output of the coprocess go to stdout
{ coproc mycoproc { awk '{print "foo" $0;fflush()}' ;} >&3 ;} 3>&1
echo bar >&${mycoproc[1]}
foobar
```
ksh has a similar feature, apparently | You may echo values to files, then the other script may read them. If you want to use it as a parameter for something, use reverse aposthrophe:
```
echo `cat storedvalue`
```
Be careful, if the two scripts are running at the same time, concurrency problems may occur, which can cause rarely appearing, mystic-looking errors. |
5,677,446 | I have two independently running scripts.
first one lets say script A calculates some values. And i want to echo these values from other script called B. These scripts will not call each other. I have used export keyword but didn't work. How can i do this? | 2011/04/15 | [
"https://Stackoverflow.com/questions/5677446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/663229/"
]
| Think of each script as a function: function A calculates some value and returns it. It does not know who will call it. Function B takes in some value and echo it. It does not care who produced that value. So, script A is:
```
#!/bin/sh
# a.sh: Calculate something and return the result
echo 19
```
and script B is:
```
#!/bin/sh
# b.sh: Consume the calculated result, which passed in as $1
echo The result is $1
```
Make them executable:
```
chmod +x [ab].sh
```
Now, we can glue them together on the command line:
```
$ b.sh $(a.sh)
The result is 19
```
Semantically, b.sh did not call a.sh. You called a.sh and passed its result to b.sh. | Actually all your need is `source` you can skip the `export` prefix.
*My use-case was an environment specific settings file, example:*
Within **main\_script.sh**
```
THIS_DIR=`dirname $0`
source $THIS_DIR/config_vars.sh
# other commands
```
Within **config\_vars.sh**
```
LOCAL_ROOT="$HOME/folder/folder"
REMOTE_USERNAME='someuser'
BACKUP_FOLDER="$LOCAL_ROOT/folder"
# etc.
``` |
5,677,446 | I have two independently running scripts.
first one lets say script A calculates some values. And i want to echo these values from other script called B. These scripts will not call each other. I have used export keyword but didn't work. How can i do this? | 2011/04/15 | [
"https://Stackoverflow.com/questions/5677446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/663229/"
]
| If I understood the requirement then can't both scripts be simply executed in same sub shell, independently but **without** calling each other or without any need of an external file or pipe like this:
Let's say this is your **script1.sh**
```
#!/bin/bash
# script1.sh: do something and finally
export x=19
```
And here us your **script2.sh**
```
#!/bin/bash
# script2.sh: read value of $x here
echo "x="${x}
```
Just call them in same sub-shell like this
```
(. ./script1.sh && ./script2.sh)
```
**OUTPUT:**
```
x=19
``` | Actually all your need is `source` you can skip the `export` prefix.
*My use-case was an environment specific settings file, example:*
Within **main\_script.sh**
```
THIS_DIR=`dirname $0`
source $THIS_DIR/config_vars.sh
# other commands
```
Within **config\_vars.sh**
```
LOCAL_ROOT="$HOME/folder/folder"
REMOTE_USERNAME='someuser'
BACKUP_FOLDER="$LOCAL_ROOT/folder"
# etc.
``` |
5,677,446 | I have two independently running scripts.
first one lets say script A calculates some values. And i want to echo these values from other script called B. These scripts will not call each other. I have used export keyword but didn't work. How can i do this? | 2011/04/15 | [
"https://Stackoverflow.com/questions/5677446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/663229/"
]
| If I understood the requirement then can't both scripts be simply executed in same sub shell, independently but **without** calling each other or without any need of an external file or pipe like this:
Let's say this is your **script1.sh**
```
#!/bin/bash
# script1.sh: do something and finally
export x=19
```
And here us your **script2.sh**
```
#!/bin/bash
# script2.sh: read value of $x here
echo "x="${x}
```
Just call them in same sub-shell like this
```
(. ./script1.sh && ./script2.sh)
```
**OUTPUT:**
```
x=19
``` | Think of each script as a function: function A calculates some value and returns it. It does not know who will call it. Function B takes in some value and echo it. It does not care who produced that value. So, script A is:
```
#!/bin/sh
# a.sh: Calculate something and return the result
echo 19
```
and script B is:
```
#!/bin/sh
# b.sh: Consume the calculated result, which passed in as $1
echo The result is $1
```
Make them executable:
```
chmod +x [ab].sh
```
Now, we can glue them together on the command line:
```
$ b.sh $(a.sh)
The result is 19
```
Semantically, b.sh did not call a.sh. You called a.sh and passed its result to b.sh. |
5,677,446 | I have two independently running scripts.
first one lets say script A calculates some values. And i want to echo these values from other script called B. These scripts will not call each other. I have used export keyword but didn't work. How can i do this? | 2011/04/15 | [
"https://Stackoverflow.com/questions/5677446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/663229/"
]
| If I understood the requirement then can't both scripts be simply executed in same sub shell, independently but **without** calling each other or without any need of an external file or pipe like this:
Let's say this is your **script1.sh**
```
#!/bin/bash
# script1.sh: do something and finally
export x=19
```
And here us your **script2.sh**
```
#!/bin/bash
# script2.sh: read value of $x here
echo "x="${x}
```
Just call them in same sub-shell like this
```
(. ./script1.sh && ./script2.sh)
```
**OUTPUT:**
```
x=19
``` | ```
mkfifo /tmp/channel
process_a.sh > /tmp/channel&
process_b.sh < /tmp/channel&
wait
```
Of course you can also just read a single line when you want it.
In bash there are coprocs, which also might be what you want. Random example from [this page](http://wiki.bash-hackers.org/syntax/keywords/coproc)
```
# let the output of the coprocess go to stdout
{ coproc mycoproc { awk '{print "foo" $0;fflush()}' ;} >&3 ;} 3>&1
echo bar >&${mycoproc[1]}
foobar
```
ksh has a similar feature, apparently |
5,677,446 | I have two independently running scripts.
first one lets say script A calculates some values. And i want to echo these values from other script called B. These scripts will not call each other. I have used export keyword but didn't work. How can i do this? | 2011/04/15 | [
"https://Stackoverflow.com/questions/5677446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/663229/"
]
| ```
mkfifo /tmp/channel
process_a.sh > /tmp/channel&
process_b.sh < /tmp/channel&
wait
```
Of course you can also just read a single line when you want it.
In bash there are coprocs, which also might be what you want. Random example from [this page](http://wiki.bash-hackers.org/syntax/keywords/coproc)
```
# let the output of the coprocess go to stdout
{ coproc mycoproc { awk '{print "foo" $0;fflush()}' ;} >&3 ;} 3>&1
echo bar >&${mycoproc[1]}
foobar
```
ksh has a similar feature, apparently | Think of each script as a function: function A calculates some value and returns it. It does not know who will call it. Function B takes in some value and echo it. It does not care who produced that value. So, script A is:
```
#!/bin/sh
# a.sh: Calculate something and return the result
echo 19
```
and script B is:
```
#!/bin/sh
# b.sh: Consume the calculated result, which passed in as $1
echo The result is $1
```
Make them executable:
```
chmod +x [ab].sh
```
Now, we can glue them together on the command line:
```
$ b.sh $(a.sh)
The result is 19
```
Semantically, b.sh did not call a.sh. You called a.sh and passed its result to b.sh. |
5,677,446 | I have two independently running scripts.
first one lets say script A calculates some values. And i want to echo these values from other script called B. These scripts will not call each other. I have used export keyword but didn't work. How can i do this? | 2011/04/15 | [
"https://Stackoverflow.com/questions/5677446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/663229/"
]
| Think of each script as a function: function A calculates some value and returns it. It does not know who will call it. Function B takes in some value and echo it. It does not care who produced that value. So, script A is:
```
#!/bin/sh
# a.sh: Calculate something and return the result
echo 19
```
and script B is:
```
#!/bin/sh
# b.sh: Consume the calculated result, which passed in as $1
echo The result is $1
```
Make them executable:
```
chmod +x [ab].sh
```
Now, we can glue them together on the command line:
```
$ b.sh $(a.sh)
The result is 19
```
Semantically, b.sh did not call a.sh. You called a.sh and passed its result to b.sh. | Can't you read a third file, let's say settings.sh with the common exported variables?
```
# common.sh
export MY_PATH=/home/foo/bar/
export VERSION=42.2a
```
and in both A and B `source common.sh` to load those values.
Note that the export may not be required in that case. |
5,677,446 | I have two independently running scripts.
first one lets say script A calculates some values. And i want to echo these values from other script called B. These scripts will not call each other. I have used export keyword but didn't work. How can i do this? | 2011/04/15 | [
"https://Stackoverflow.com/questions/5677446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/663229/"
]
| ```
mkfifo /tmp/channel
process_a.sh > /tmp/channel&
process_b.sh < /tmp/channel&
wait
```
Of course you can also just read a single line when you want it.
In bash there are coprocs, which also might be what you want. Random example from [this page](http://wiki.bash-hackers.org/syntax/keywords/coproc)
```
# let the output of the coprocess go to stdout
{ coproc mycoproc { awk '{print "foo" $0;fflush()}' ;} >&3 ;} 3>&1
echo bar >&${mycoproc[1]}
foobar
```
ksh has a similar feature, apparently | Can't you read a third file, let's say settings.sh with the common exported variables?
```
# common.sh
export MY_PATH=/home/foo/bar/
export VERSION=42.2a
```
and in both A and B `source common.sh` to load those values.
Note that the export may not be required in that case. |
4,257,267 | Let's say you have parameters(s) in your LINQ query where clause, how do you handle that?
Here is an example:
```
var peoples= from i in individuals
where (string.IsNullOrEmpty(lastName) i.LastName.Equals(lastName))
select i;
``` | 2010/11/23 | [
"https://Stackoverflow.com/questions/4257267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/449897/"
]
| Try to understand what's going on under the hood:
* How query expressions are translated by the compiler
* How LINQ to Objects streams its data, and how it defers execution
* How queries execute remotely via IQueryable and expression trees
It's also worth becoming comfortable with both query expressions, e.g.
```
var query = from person in people
where person.IsAdult
select person.Name;
```
and "dot notation":
```
var query = people.Where(person => person.IsAdult)
.Select(person => person.Name);
```
Knowing both will let you choose the most readable form for any particular query. | [101 LinQ Samples](http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx) you can start with samples from MSDN |
4,257,267 | Let's say you have parameters(s) in your LINQ query where clause, how do you handle that?
Here is an example:
```
var peoples= from i in individuals
where (string.IsNullOrEmpty(lastName) i.LastName.Equals(lastName))
select i;
``` | 2010/11/23 | [
"https://Stackoverflow.com/questions/4257267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/449897/"
]
| [101 LinQ Samples](http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx) you can start with samples from MSDN | The best advice I could offer someone just starting with `LINQ` is get [`LINQPad`](http://www.linqpad.net/). It is an invaluable tool and will speed up your learning process significantly. And it comes with lots and lots of samples that demonstrate, and let you work with, all the `LINQ` operators. |
4,257,267 | Let's say you have parameters(s) in your LINQ query where clause, how do you handle that?
Here is an example:
```
var peoples= from i in individuals
where (string.IsNullOrEmpty(lastName) i.LastName.Equals(lastName))
select i;
``` | 2010/11/23 | [
"https://Stackoverflow.com/questions/4257267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/449897/"
]
| [101 LinQ Samples](http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx) you can start with samples from MSDN | You do it in LINQ like you would do in "normal" C#.
In your sample you used string.IsNullOrEmpty(), so you don't differentiate between null and "". If that's the case you could write sth. like the following:
```
if ((lastName ?? "") == (i.LastName ?? ""))
{
// equal
}
```
Note: [The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.](http://msdn.microsoft.com/en-US/library/ms173224%28VS.80%29.aspx)
You can integrate that logic into your LINQ query as follows:
```
var peoples = from i in individuals
where (lastName ?? "") == (i.LastName ?? "")
select i;
``` |
4,257,267 | Let's say you have parameters(s) in your LINQ query where clause, how do you handle that?
Here is an example:
```
var peoples= from i in individuals
where (string.IsNullOrEmpty(lastName) i.LastName.Equals(lastName))
select i;
``` | 2010/11/23 | [
"https://Stackoverflow.com/questions/4257267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/449897/"
]
| Try to understand what's going on under the hood:
* How query expressions are translated by the compiler
* How LINQ to Objects streams its data, and how it defers execution
* How queries execute remotely via IQueryable and expression trees
It's also worth becoming comfortable with both query expressions, e.g.
```
var query = from person in people
where person.IsAdult
select person.Name;
```
and "dot notation":
```
var query = people.Where(person => person.IsAdult)
.Select(person => person.Name);
```
Knowing both will let you choose the most readable form for any particular query. | The result of a query expression is *a query object*, not *the results of the query*. If you want the results, you can ask the query object to start proffering up results. That is, when you say:
```
var names = from c in customers where c.City == "London" select c.Name;
```
then names is *a query object* that represents "get me the names of all the customers in London". It is *not* a sequence in memory of all the names of customers who live in London; the results of the query are computed on-demand. It is not until you say:
```
foreach(var name in names) ...
```
that the actual results are computed.
This means that if you ask the same query object for its results twice, the answer might be different. The customers list might have been changed between the first time you ask and the second time you ask. Because queries defer getting their results, you always get fresh results. But you sometimes do the same work twice. |
4,257,267 | Let's say you have parameters(s) in your LINQ query where clause, how do you handle that?
Here is an example:
```
var peoples= from i in individuals
where (string.IsNullOrEmpty(lastName) i.LastName.Equals(lastName))
select i;
``` | 2010/11/23 | [
"https://Stackoverflow.com/questions/4257267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/449897/"
]
| Try to understand what's going on under the hood:
* How query expressions are translated by the compiler
* How LINQ to Objects streams its data, and how it defers execution
* How queries execute remotely via IQueryable and expression trees
It's also worth becoming comfortable with both query expressions, e.g.
```
var query = from person in people
where person.IsAdult
select person.Name;
```
and "dot notation":
```
var query = people.Where(person => person.IsAdult)
.Select(person => person.Name);
```
Knowing both will let you choose the most readable form for any particular query. | The best advice I could offer someone just starting with `LINQ` is get [`LINQPad`](http://www.linqpad.net/). It is an invaluable tool and will speed up your learning process significantly. And it comes with lots and lots of samples that demonstrate, and let you work with, all the `LINQ` operators. |
4,257,267 | Let's say you have parameters(s) in your LINQ query where clause, how do you handle that?
Here is an example:
```
var peoples= from i in individuals
where (string.IsNullOrEmpty(lastName) i.LastName.Equals(lastName))
select i;
``` | 2010/11/23 | [
"https://Stackoverflow.com/questions/4257267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/449897/"
]
| Try to understand what's going on under the hood:
* How query expressions are translated by the compiler
* How LINQ to Objects streams its data, and how it defers execution
* How queries execute remotely via IQueryable and expression trees
It's also worth becoming comfortable with both query expressions, e.g.
```
var query = from person in people
where person.IsAdult
select person.Name;
```
and "dot notation":
```
var query = people.Where(person => person.IsAdult)
.Select(person => person.Name);
```
Knowing both will let you choose the most readable form for any particular query. | You do it in LINQ like you would do in "normal" C#.
In your sample you used string.IsNullOrEmpty(), so you don't differentiate between null and "". If that's the case you could write sth. like the following:
```
if ((lastName ?? "") == (i.LastName ?? ""))
{
// equal
}
```
Note: [The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.](http://msdn.microsoft.com/en-US/library/ms173224%28VS.80%29.aspx)
You can integrate that logic into your LINQ query as follows:
```
var peoples = from i in individuals
where (lastName ?? "") == (i.LastName ?? "")
select i;
``` |
4,257,267 | Let's say you have parameters(s) in your LINQ query where clause, how do you handle that?
Here is an example:
```
var peoples= from i in individuals
where (string.IsNullOrEmpty(lastName) i.LastName.Equals(lastName))
select i;
``` | 2010/11/23 | [
"https://Stackoverflow.com/questions/4257267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/449897/"
]
| The result of a query expression is *a query object*, not *the results of the query*. If you want the results, you can ask the query object to start proffering up results. That is, when you say:
```
var names = from c in customers where c.City == "London" select c.Name;
```
then names is *a query object* that represents "get me the names of all the customers in London". It is *not* a sequence in memory of all the names of customers who live in London; the results of the query are computed on-demand. It is not until you say:
```
foreach(var name in names) ...
```
that the actual results are computed.
This means that if you ask the same query object for its results twice, the answer might be different. The customers list might have been changed between the first time you ask and the second time you ask. Because queries defer getting their results, you always get fresh results. But you sometimes do the same work twice. | The best advice I could offer someone just starting with `LINQ` is get [`LINQPad`](http://www.linqpad.net/). It is an invaluable tool and will speed up your learning process significantly. And it comes with lots and lots of samples that demonstrate, and let you work with, all the `LINQ` operators. |
4,257,267 | Let's say you have parameters(s) in your LINQ query where clause, how do you handle that?
Here is an example:
```
var peoples= from i in individuals
where (string.IsNullOrEmpty(lastName) i.LastName.Equals(lastName))
select i;
``` | 2010/11/23 | [
"https://Stackoverflow.com/questions/4257267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/449897/"
]
| The result of a query expression is *a query object*, not *the results of the query*. If you want the results, you can ask the query object to start proffering up results. That is, when you say:
```
var names = from c in customers where c.City == "London" select c.Name;
```
then names is *a query object* that represents "get me the names of all the customers in London". It is *not* a sequence in memory of all the names of customers who live in London; the results of the query are computed on-demand. It is not until you say:
```
foreach(var name in names) ...
```
that the actual results are computed.
This means that if you ask the same query object for its results twice, the answer might be different. The customers list might have been changed between the first time you ask and the second time you ask. Because queries defer getting their results, you always get fresh results. But you sometimes do the same work twice. | You do it in LINQ like you would do in "normal" C#.
In your sample you used string.IsNullOrEmpty(), so you don't differentiate between null and "". If that's the case you could write sth. like the following:
```
if ((lastName ?? "") == (i.LastName ?? ""))
{
// equal
}
```
Note: [The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.](http://msdn.microsoft.com/en-US/library/ms173224%28VS.80%29.aspx)
You can integrate that logic into your LINQ query as follows:
```
var peoples = from i in individuals
where (lastName ?? "") == (i.LastName ?? "")
select i;
``` |
33,641 | What constitutes a Streak Bonus? This is in relation to obtaining the Combat Efficiency Ribbon, which states that you have to obtain 3 Streak Bonuses in a round. | 2011/10/29 | [
"https://gaming.stackexchange.com/questions/33641",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/306/"
]
| Combat Efficiency Ribbon
500 XP Bonus. Get 3 Kill Streaks in one round. To get a streak, you need to kill 8 times in a row without dying yourself. Get 3 Kill Streaks of 8 to unlock this ribbon, try playing on infantry heavy maps to increase your chances early on.
Per <http://www.gamefront.com/battlefield-3-ribbons-guide/> | After 5 kills without dying, every 3rd thereafter is considered to extend the 'streak'.
Thus, to get three in a row, it would be 14 kills. (5 +3 +3 +3 = 14) |
33,641 | What constitutes a Streak Bonus? This is in relation to obtaining the Combat Efficiency Ribbon, which states that you have to obtain 3 Streak Bonuses in a round. | 2011/10/29 | [
"https://gaming.stackexchange.com/questions/33641",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/306/"
]
| The wording on the bonus is really silly (same goes for the Nemesis ribbon). Once you get 5 kills, you're considered to be a on Combat Efficiency streak. Your 6th kill gives you a 1 streak bonus, 7th kill gives you 2 streak bonus and 8th gives you a 3 streak bonus and hence the ribbon.
It is possible to get multiple ribbons in the one life. Once you have got the first one, (I think) you will get the next one for every 3 subsequent kills in that life.
So if you go on a 23 kill streak you are going to 6 get of these ribbons (8 + 3 + 3 + 3 + 3 + 3) | Combat Efficiency Ribbon
500 XP Bonus. Get 3 Kill Streaks in one round. To get a streak, you need to kill 8 times in a row without dying yourself. Get 3 Kill Streaks of 8 to unlock this ribbon, try playing on infantry heavy maps to increase your chances early on.
Per <http://www.gamefront.com/battlefield-3-ribbons-guide/> |
33,641 | What constitutes a Streak Bonus? This is in relation to obtaining the Combat Efficiency Ribbon, which states that you have to obtain 3 Streak Bonuses in a round. | 2011/10/29 | [
"https://gaming.stackexchange.com/questions/33641",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/306/"
]
| The wording on the bonus is really silly (same goes for the Nemesis ribbon). Once you get 5 kills, you're considered to be a on Combat Efficiency streak. Your 6th kill gives you a 1 streak bonus, 7th kill gives you 2 streak bonus and 8th gives you a 3 streak bonus and hence the ribbon.
It is possible to get multiple ribbons in the one life. Once you have got the first one, (I think) you will get the next one for every 3 subsequent kills in that life.
So if you go on a 23 kill streak you are going to 6 get of these ribbons (8 + 3 + 3 + 3 + 3 + 3) | After 5 kills without dying, every 3rd thereafter is considered to extend the 'streak'.
Thus, to get three in a row, it would be 14 kills. (5 +3 +3 +3 = 14) |
18,229,890 | I need to make a custom code which will help me to find location of a particular IP entered through a text box.
When I searched the internet what I found is only providing automatic detection of IP and it's location. Please help me. | 2013/08/14 | [
"https://Stackoverflow.com/questions/18229890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2682127/"
]
| Here you go.
<http://jsfiddle.net/GLjND/3/> (the yellow background is just so you can see the new div)
Just give the divs
```
display: table-cell
```
and you're done. | Here it is - [**fiddle**](http://jsfiddle.net/deepakb/zan9X/4/)
```
<div id="wrapper">
<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
</div>
body{
padding:0;
margin:0;
}
#wrapper{
width:500px;
height:auto;
background:red;
}
#first{
display: table-cell;
width:230px;
height:300px;
background:blue;
}
#second{
display: table-cell;
background:white;
border-left: thick dotted #ff0000;
}
#third{
display: table-cell;
width:270px;
height:350px;
background:green;
}
``` |
18,229,890 | I need to make a custom code which will help me to find location of a particular IP entered through a text box.
When I searched the internet what I found is only providing automatic detection of IP and it's location. Please help me. | 2013/08/14 | [
"https://Stackoverflow.com/questions/18229890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2682127/"
]
| Here you go.
<http://jsfiddle.net/GLjND/3/> (the yellow background is just so you can see the new div)
Just give the divs
```
display: table-cell
```
and you're done. | When you are using float property, i recommend you to set overflow:hidden to the parent div
```
#wrapper{
overflow:hidden;
}
```
And for the #second u have set the height to 100%, for this to work u should fix an height for the parent div
```
#wrapper{
height:400px;
}
```
Here is the [Jsfiddle](http://jsfiddle.net/zan9X/5/)
Hope this will a good solution and will be more informative |
18,229,890 | I need to make a custom code which will help me to find location of a particular IP entered through a text box.
When I searched the internet what I found is only providing automatic detection of IP and it's location. Please help me. | 2013/08/14 | [
"https://Stackoverflow.com/questions/18229890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2682127/"
]
| Here you go.
<http://jsfiddle.net/GLjND/3/> (the yellow background is just so you can see the new div)
Just give the divs
```
display: table-cell
```
and you're done. | Just give the CSS property:
```
overflow : hidden
display : table-cell
``` |
14,002 | I am working recognition of plant seeds with Matlab, and I am looking for code to remove the shadow in grayscale and binary.

The binarized version of the image is:
 | 2014/01/25 | [
"https://dsp.stackexchange.com/questions/14002",
"https://dsp.stackexchange.com",
"https://dsp.stackexchange.com/users/7673/"
]
| This question seems to be based on several misconceptions.
In a QPSK modulator operating at a rate of $N$ baud, *two* bits enter the
modulator during each $T = N^{-1}$ second interval. If the bits are
entering on a single wire (at a rate of $2N$ bits per second, the
QPSK modulator first *converts* this serial input
bit stream at $2N$ bits per second into two parallel bit streams at
$N$ bits per second. For example, alternate bits are steered to
alternate streams so that, *say,* all the odd-numbered bits
are in one stream and all the even-numbered bits are in the
other stream.
In some cases, the bits entering the QPSK modulator
are already formatted into two parallel bit streams at $N$ bits per
second. One important and commonly observed arrangement of this type
is when a rate-$\frac12$ convolutional encoder precedes the QPSK modulator,
so that *information* bits enter the encoder serially
at rate $N$ bits per second, and the convolutional encoder spits out two
*parallel* bit streams at $N$ bits per second. However, regardless of
encoding or not, the bits that the QPSK
modulator uses are in two parallel streams that are *synchronous*
(that is, the bit transitions occur at the same times (once every
$T$ seconds) and in each
bit stream, the bit occupies the entire $T$ second interval.
As the OP's question says, the bits are modulated onto cosine and
sine carriers. As discussed in more detail [here](https://dsp.stackexchange.com/a/6447/235), if the bits in the two streams are denoted by $b\_I$ and
$b\_Q$, then the corresponding signals, **say, over the interval
$[0,T)$** can be taken to be
$$(-1)^{b\_I}\cos(2\pi f\_c t) ~~ \text{and}~~ -(-1)^{b\_Q}\sin(2\pi f\_c t),
0 \leq t < T. \tag{1}$$
(Ignore the negative sign on the $\sin$, it is there to simplify
notation in more detailed analyses). The QPSK signal is the **sum**
$$(-1)^{b\_I}\cos(2\pi f\_c t) -(-1)^{b\_Q}\sin(2\pi f\_c t),
0 \leq t \leq T. \tag{2}$$
**It is not the case, as the OP seems to think** that the two
signals are separated into even and odd bits, so that
$(-1)^{b\_I}\cos(2\pi f\_c t)$ lasts from $t=0$ to $t=T/2$ and
$-(-1)^{b\_Q}\sin(2\pi f\_c t)$ from $t=T/2$ to $t=T$: the
cosine and sine signals last for the full $T$-second duration
and the bits $b\_I$ and $b\_Q$ both affect the signal phase for all
$T$ seconds.
Offset QPSK *also* converts the serial bit stream into
two parallel bit streams in which the bit intervals are
of duration $T$ on each wire, but the bit *transitions*
are **not synchronous** but occur with an *offset* of
$T/2$ seconds. Thus, $b\_I$ modulates the cosine carrier
to produce
$$(-1)^{b\_I}\cos(2\pi f\_c t), 0 \leq t < T$$
but $b\_Q$ modulates the sine carrier to produce
$$-(-1)^{b\_Q}\sin(2\pi f\_c t), \frac{T}{2} \leq t < \frac{3T}{2}.$$
The modulator output is *still* the sum of the two sinusoids,
but the sinusoids change phase at different times. In fact,
the signal can be deemed to be a $2N$ baud signal since the
phase can change once every $T/2 = (2N)^{-1}$ seconds.
Each bit still affects the phase for $T$ seconds, but the
bit transitions are staggered. In the receiver, integrations
(or matched filterings)
are carried out over (staggered) $T$-second intervals in the
two branches of the receiver, and the decision devices
spit out one bit every $T$ seconds but at staggered times.
It is easy to multiplex these decisions onto a single wire
that thus carries a bit stream at $2N$ bits per second,
just as the input to the QPSK modulator (if anyone still
remembers that far back in this answer) is a bit stream
on a single wire at $2N$ bits per second. | sure, in reception of QPSK, you receive bit pairs as they are transmitted, and detangle them in the reverse manner that they were grouped together.
what's really cool about OQPSK is that the order of the bits going in can **naturally** determine the order of bit changing in OQPSK. in fact, it can be made into a DSP modulation system *without* the need for grouping bits together in pairs.
define the bitstream $a[n] \in \{0,1\}$, and the bipolar binary signal as:
$$ x[n] \ = \ (-1)^{a[n]} \ = \ 1 - 2 a[n]\ \in \ \{+1,-1\} $$
then define these two gating functions:
even samples:
$$ g[n] \ = \ \tfrac{1}{2} \left(1 + (-1)^n \right) \ = \ \tfrac{1}{2} \left(1 + e^{j \pi n} \right) \ = \ \begin{cases}
1, & n\text{ even} \\
0, & n\text{ odd}
\end{cases} $$
odd samples:
$$ 1 - g[n] \ = \ g[n-1] \ = \ \tfrac{1}{2} \left(1 - (-1)^n \right) \ = \ \tfrac{1}{2} \left(1 - e^{j \pi n} \right) \ = \ \begin{cases}
0, & n\text{ even} \\
1, & n\text{ odd}
\end{cases} $$
the I/Q quadrature pair is:
$$ i[n] \ = \ g[n] \ x[n] \ + \ (1-g[n]) \ x[n-1] $$
$$ q[n] \ = \ (1-g[n]) \ x[n] \ + \ g[n] \ x[n-1] $$
note that $i[n+1]=i[n]=x[n]$ for even $n$ and $q[n+1]=q[n]=x[n]$ for odd $n$. so for either $i[n]$ or $q[n]$, the bit rate is half the bit rate is for $a[n]$ or $x[n]$. so the bandwidth needed for the analog reconstructed signals $i(t)$ and $q(t)$ need only be half of the bandwidth needed for the reconstruction of $x(t)$ from $x[n]$ is.
then the discrete-time OQPSK modulating signal is
$$ s[n] \ = \ i[n] \ + \ j \ q[n] $$
returning to the real $i[n]$ and $q[n]$:
$$\begin{align}
i[n] \ & = \ g[n] \ x[n] \ + \ (1-g[n]) \ x[n-1] \\
& = \ \tfrac{1}{2} \left(1 + e^{j \pi n} \right) \ x[n] \ + \ \tfrac{1}{2} \left(1 - e^{j \pi n} \right) \ x[n-1] \\
& = \ \tfrac{1}{2} (x[n] + x[n-1]) \ + \ \tfrac{1}{2} e^{j \pi n} (x[n] - x[n-1]) \\
\end{align}$$
$$\begin{align}
q[n] \ & = \ (1-g[n]) \ x[n] \ + \ g[n] \ x[n-1] \\
& = \ \tfrac{1}{2} \left(1 - e^{j \pi n} \right) \ x[n] \ + \ \tfrac{1}{2} \left(1 + e^{j \pi n} \right) \ x[n-1] \\
& = \ \tfrac{1}{2} (x[n] + x[n-1]) \ - \ \tfrac{1}{2} e^{j \pi n} (x[n] - x[n-1]) \\
\end{align}$$
the OQPSK modulating signal is
$$\begin{align}
s[n] \ & = \ i[n] \ + \ j \ q[n] \\
& = \ \tfrac{1}{2} (x[n] + x[n-1]) \ + \ \tfrac{1}{2} e^{j \pi n} (x[n] - x[n-1]) \ + \ j \ \left( \tfrac{1}{2} (x[n] + x[n-1]) \ - \ \tfrac{1}{2} e^{j \pi n} (x[n] - x[n-1]) \right) \\
& = \ \frac{1+j}{2} (x[n] + x[n-1]) \ + \ \frac{1-j}{2} e^{j \pi n} (x[n] - x[n-1]) \\
\end{align}$$
now compute the Discrete-time Fourier Transform (DTFT)
$$\begin{align}
S(\omega) \ & = \ \frac{1+j}{2} \left(X(\omega) + e^{-j\omega}X(\omega) \right) \ + \ \frac{1-j}{2} \left(X(\omega-\pi) - e^{-j(\omega-\pi)}X(\omega-\pi) \right) \\
& = \ \frac{1+j}{2} X(\omega) \left(1 + e^{-j\omega} \right) \ + \ \frac{1-j}{2} X(\omega-\pi) \left(1 - e^{-j(\omega-\pi)} \right) \\
& = \ \frac{1+j}{2} X(\omega) \left(1 + e^{-j\omega} \right) \ + \ \frac{1-j}{2} X(\omega-\pi) \left(1 + e^{-j\omega} \right) \\
& = \ \frac{1 + e^{-j\omega}}{2} \Big( (1+j)X(\omega) \ + \ (1-j)X(\omega-\pi) \Big) \\
& = \ e^{-j\omega/2}\frac{e^{j\omega/2} + e^{-j\omega/2}}{2} \Big( (1+j)X(\omega) \ + \ (1-j)X(\omega-\pi) \Big) \\
& = \ e^{-j\omega/2} \ \cos(\omega/2) \ \Big( (1+j)X(\omega) \ + \ (1-j)X(\omega-\pi) \Big) \\
\end{align}$$
so the next question to ask is what does the spectrum of $X(\omega)$ look like for a bit stream $a[n]$ that looks like 00000000...? or 11111111...? or 01010101...? or 10101010...? or 00110011...? or 01100110...? and then what is the spectrum of the quadrature modulating signal $S(\omega)$ with those same bit sequences for $a[n]$? |
1,342,213 | Is it possible to get the raw HTTP Request from the HttpServletRequest object? I want to see the raw request as a String if at all possible.
I need to get the full text of the request, in this case it's a POST request, so the URL doesn't help. It's also part of a multi-part form, so I can't just call the "getParameterNames()" or "getParameterValues()".
Thank you, | 2009/08/27 | [
"https://Stackoverflow.com/questions/1342213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32812/"
]
| Well, it sounds like you are doing some sort of troubleshooting. Why not just drop the multi-part form component while you are looking at the raw form data. You can use the following JSP snippet to construct the form data.
```
<%
Enumeration en = request.getParameterNames();
String str = "";
while(en.hasMoreElements()){
String paramName = (String)en.nextElement();
String paramValue = request.getParameter(paramName);
str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
}
if (str.length()>0)
str = str.substring(1);
%>
``` | Sounds like you need a [servlet filter](http://java.sun.com/javaee/5/docs/api/javax/servlet/Filter.html). There is no standard way to handle `multipart/form-data`, so you'll have to take care to cache this data appropriately when [wrapping the HttpServletRequest](http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletRequestWrapper.html). |
1,342,213 | Is it possible to get the raw HTTP Request from the HttpServletRequest object? I want to see the raw request as a String if at all possible.
I need to get the full text of the request, in this case it's a POST request, so the URL doesn't help. It's also part of a multi-part form, so I can't just call the "getParameterNames()" or "getParameterValues()".
Thank you, | 2009/08/27 | [
"https://Stackoverflow.com/questions/1342213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32812/"
]
| You can read the raw HTTP request by doing:
```
ServletInputStream in = request.getInputStream();
```
and then use the regular `read`methods of the InputStream.
Hope that helps. | Sounds like you need a [servlet filter](http://java.sun.com/javaee/5/docs/api/javax/servlet/Filter.html). There is no standard way to handle `multipart/form-data`, so you'll have to take care to cache this data appropriately when [wrapping the HttpServletRequest](http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletRequestWrapper.html). |
1,342,213 | Is it possible to get the raw HTTP Request from the HttpServletRequest object? I want to see the raw request as a String if at all possible.
I need to get the full text of the request, in this case it's a POST request, so the URL doesn't help. It's also part of a multi-part form, so I can't just call the "getParameterNames()" or "getParameterValues()".
Thank you, | 2009/08/27 | [
"https://Stackoverflow.com/questions/1342213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32812/"
]
| Sounds like you need a [servlet filter](http://java.sun.com/javaee/5/docs/api/javax/servlet/Filter.html). There is no standard way to handle `multipart/form-data`, so you'll have to take care to cache this data appropriately when [wrapping the HttpServletRequest](http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletRequestWrapper.html). | If you want to get the whole request to a String you can do it with one line of code using the apache IOUtils library.
```
String myString = org.apache.commons.io.IOUtils.toString(request.getInputStream());
``` |
1,342,213 | Is it possible to get the raw HTTP Request from the HttpServletRequest object? I want to see the raw request as a String if at all possible.
I need to get the full text of the request, in this case it's a POST request, so the URL doesn't help. It's also part of a multi-part form, so I can't just call the "getParameterNames()" or "getParameterValues()".
Thank you, | 2009/08/27 | [
"https://Stackoverflow.com/questions/1342213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32812/"
]
| Well, it sounds like you are doing some sort of troubleshooting. Why not just drop the multi-part form component while you are looking at the raw form data. You can use the following JSP snippet to construct the form data.
```
<%
Enumeration en = request.getParameterNames();
String str = "";
while(en.hasMoreElements()){
String paramName = (String)en.nextElement();
String paramValue = request.getParameter(paramName);
str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
}
if (str.length()>0)
str = str.substring(1);
%>
``` | or if you can write some interceptor to convert the parameter names and values to string format object and set it in request context, or filter is a good idea too. |
1,342,213 | Is it possible to get the raw HTTP Request from the HttpServletRequest object? I want to see the raw request as a String if at all possible.
I need to get the full text of the request, in this case it's a POST request, so the URL doesn't help. It's also part of a multi-part form, so I can't just call the "getParameterNames()" or "getParameterValues()".
Thank you, | 2009/08/27 | [
"https://Stackoverflow.com/questions/1342213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32812/"
]
| You can read the raw HTTP request by doing:
```
ServletInputStream in = request.getInputStream();
```
and then use the regular `read`methods of the InputStream.
Hope that helps. | or if you can write some interceptor to convert the parameter names and values to string format object and set it in request context, or filter is a good idea too. |
1,342,213 | Is it possible to get the raw HTTP Request from the HttpServletRequest object? I want to see the raw request as a String if at all possible.
I need to get the full text of the request, in this case it's a POST request, so the URL doesn't help. It's also part of a multi-part form, so I can't just call the "getParameterNames()" or "getParameterValues()".
Thank you, | 2009/08/27 | [
"https://Stackoverflow.com/questions/1342213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32812/"
]
| or if you can write some interceptor to convert the parameter names and values to string format object and set it in request context, or filter is a good idea too. | If you want to get the whole request to a String you can do it with one line of code using the apache IOUtils library.
```
String myString = org.apache.commons.io.IOUtils.toString(request.getInputStream());
``` |
1,342,213 | Is it possible to get the raw HTTP Request from the HttpServletRequest object? I want to see the raw request as a String if at all possible.
I need to get the full text of the request, in this case it's a POST request, so the URL doesn't help. It's also part of a multi-part form, so I can't just call the "getParameterNames()" or "getParameterValues()".
Thank you, | 2009/08/27 | [
"https://Stackoverflow.com/questions/1342213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32812/"
]
| You can read the raw HTTP request by doing:
```
ServletInputStream in = request.getInputStream();
```
and then use the regular `read`methods of the InputStream.
Hope that helps. | Well, it sounds like you are doing some sort of troubleshooting. Why not just drop the multi-part form component while you are looking at the raw form data. You can use the following JSP snippet to construct the form data.
```
<%
Enumeration en = request.getParameterNames();
String str = "";
while(en.hasMoreElements()){
String paramName = (String)en.nextElement();
String paramValue = request.getParameter(paramName);
str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
}
if (str.length()>0)
str = str.substring(1);
%>
``` |
1,342,213 | Is it possible to get the raw HTTP Request from the HttpServletRequest object? I want to see the raw request as a String if at all possible.
I need to get the full text of the request, in this case it's a POST request, so the URL doesn't help. It's also part of a multi-part form, so I can't just call the "getParameterNames()" or "getParameterValues()".
Thank you, | 2009/08/27 | [
"https://Stackoverflow.com/questions/1342213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32812/"
]
| Well, it sounds like you are doing some sort of troubleshooting. Why not just drop the multi-part form component while you are looking at the raw form data. You can use the following JSP snippet to construct the form data.
```
<%
Enumeration en = request.getParameterNames();
String str = "";
while(en.hasMoreElements()){
String paramName = (String)en.nextElement();
String paramValue = request.getParameter(paramName);
str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
}
if (str.length()>0)
str = str.substring(1);
%>
``` | If you want to get the whole request to a String you can do it with one line of code using the apache IOUtils library.
```
String myString = org.apache.commons.io.IOUtils.toString(request.getInputStream());
``` |
1,342,213 | Is it possible to get the raw HTTP Request from the HttpServletRequest object? I want to see the raw request as a String if at all possible.
I need to get the full text of the request, in this case it's a POST request, so the URL doesn't help. It's also part of a multi-part form, so I can't just call the "getParameterNames()" or "getParameterValues()".
Thank you, | 2009/08/27 | [
"https://Stackoverflow.com/questions/1342213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32812/"
]
| You can read the raw HTTP request by doing:
```
ServletInputStream in = request.getInputStream();
```
and then use the regular `read`methods of the InputStream.
Hope that helps. | If you want to get the whole request to a String you can do it with one line of code using the apache IOUtils library.
```
String myString = org.apache.commons.io.IOUtils.toString(request.getInputStream());
``` |
3,093,150 | I'm looking for a browser extension (Firefox, Chrome) allowing to replace a Javascript file on a live Web site to do some testing/hacking.
Basically, it should take a URL and load another one instead (locally or on a HTTP development server).
Any idea? | 2010/06/22 | [
"https://Stackoverflow.com/questions/3093150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044/"
]
| Not sure if this helps or not, but I just encountered a chrome plugin called Resource Override, which sounds like it does something similar. Im trying out the Fiddler which someone else mentioned, but I think i'm also going to try this one at some point. <https://chrome.google.com/webstore/detail/resource-override/pkoacgokdfckfpndoffpifphamojphii?hl=en> | There is [https everywhere which lets you define rules for url rewrites](https://www.eff.org/https-everywhere/rulesets). This should work on all request, including script requests.
[Tamper](https://addons.mozilla.org/en-us/firefox/addon/tamper-data/) data might do the job, but I don't know how automated/permanent you can set it up.
And there is also an extension called [redirector](https://addons.mozilla.org/en-us/firefox/addon/redirector/). I didn't test that one. Potentially it only works on the address bar.
Update:
That is unfortunate. In that case probably a proxy is you only way. What about a firefox extension that is a proxy, like [Foxyproxy](http://getfoxyproxy.org/) |
3,093,150 | I'm looking for a browser extension (Firefox, Chrome) allowing to replace a Javascript file on a live Web site to do some testing/hacking.
Basically, it should take a URL and load another one instead (locally or on a HTTP development server).
Any idea? | 2010/06/22 | [
"https://Stackoverflow.com/questions/3093150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044/"
]
| Try <http://www.fiddler2.com/fiddler2/version.asp>
It does that and much more. But it's not a browser extension. | I think this is a task for a personal proxy. You can sniff traffic on the proxy and apply rules to modify requests/content |
3,093,150 | I'm looking for a browser extension (Firefox, Chrome) allowing to replace a Javascript file on a live Web site to do some testing/hacking.
Basically, it should take a URL and load another one instead (locally or on a HTTP development server).
Any idea? | 2010/06/22 | [
"https://Stackoverflow.com/questions/3093150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044/"
]
| Try <http://www.fiddler2.com/fiddler2/version.asp>
It does that and much more. But it's not a browser extension. | Disclaimer: I'm the author of the software :-)
A different approach that *might* suit your usecase better is to use a RoboHydra-based development proxy. The idea here would be that you want to keep ALL Javascript files in your machine, and use another server simply as a backend. It's great for eg. front-end developers that don't want to have the whole backend installed in their machines.
You can see the documentation, tutorials and such at <http://robohydra.org/>, and have an article describing exactly that usecase at <http://dev.opera.com/articles/view/robohydra-a-new-testing-tool-for-client-server-interactions/>.
However, as of now it can't proxy to HTTPS URLs, but that should be a trivial change that I intend to do soon anyway. |
3,093,150 | I'm looking for a browser extension (Firefox, Chrome) allowing to replace a Javascript file on a live Web site to do some testing/hacking.
Basically, it should take a URL and load another one instead (locally or on a HTTP development server).
Any idea? | 2010/06/22 | [
"https://Stackoverflow.com/questions/3093150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044/"
]
| Not sure if this helps or not, but I just encountered a chrome plugin called Resource Override, which sounds like it does something similar. Im trying out the Fiddler which someone else mentioned, but I think i'm also going to try this one at some point. <https://chrome.google.com/webstore/detail/resource-override/pkoacgokdfckfpndoffpifphamojphii?hl=en> | How about [Greasemonkey](https://addons.mozilla.org/de/firefox/addon/greasemonkey/)?
That should be the thing you're searching for! |
3,093,150 | I'm looking for a browser extension (Firefox, Chrome) allowing to replace a Javascript file on a live Web site to do some testing/hacking.
Basically, it should take a URL and load another one instead (locally or on a HTTP development server).
Any idea? | 2010/06/22 | [
"https://Stackoverflow.com/questions/3093150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044/"
]
| Not sure if this helps or not, but I just encountered a chrome plugin called Resource Override, which sounds like it does something similar. Im trying out the Fiddler which someone else mentioned, but I think i'm also going to try this one at some point. <https://chrome.google.com/webstore/detail/resource-override/pkoacgokdfckfpndoffpifphamojphii?hl=en> | Disclaimer: I'm the author of the software :-)
A different approach that *might* suit your usecase better is to use a RoboHydra-based development proxy. The idea here would be that you want to keep ALL Javascript files in your machine, and use another server simply as a backend. It's great for eg. front-end developers that don't want to have the whole backend installed in their machines.
You can see the documentation, tutorials and such at <http://robohydra.org/>, and have an article describing exactly that usecase at <http://dev.opera.com/articles/view/robohydra-a-new-testing-tool-for-client-server-interactions/>.
However, as of now it can't proxy to HTTPS URLs, but that should be a trivial change that I intend to do soon anyway. |
3,093,150 | I'm looking for a browser extension (Firefox, Chrome) allowing to replace a Javascript file on a live Web site to do some testing/hacking.
Basically, it should take a URL and load another one instead (locally or on a HTTP development server).
Any idea? | 2010/06/22 | [
"https://Stackoverflow.com/questions/3093150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044/"
]
| I think this is a task for a personal proxy. You can sniff traffic on the proxy and apply rules to modify requests/content | You should probably consider [robohydra](http://dev.opera.com/articles/view/robohydra-a-new-testing-tool-for-client-server-interactions/), since it is specifically developed for your case. They do not support https yet, but they are open to including it in the future. |
3,093,150 | I'm looking for a browser extension (Firefox, Chrome) allowing to replace a Javascript file on a live Web site to do some testing/hacking.
Basically, it should take a URL and load another one instead (locally or on a HTTP development server).
Any idea? | 2010/06/22 | [
"https://Stackoverflow.com/questions/3093150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044/"
]
| Try <http://www.fiddler2.com/fiddler2/version.asp>
It does that and much more. But it's not a browser extension. | Not sure if this helps or not, but I just encountered a chrome plugin called Resource Override, which sounds like it does something similar. Im trying out the Fiddler which someone else mentioned, but I think i'm also going to try this one at some point. <https://chrome.google.com/webstore/detail/resource-override/pkoacgokdfckfpndoffpifphamojphii?hl=en> |
3,093,150 | I'm looking for a browser extension (Firefox, Chrome) allowing to replace a Javascript file on a live Web site to do some testing/hacking.
Basically, it should take a URL and load another one instead (locally or on a HTTP development server).
Any idea? | 2010/06/22 | [
"https://Stackoverflow.com/questions/3093150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044/"
]
| Alternatives:
* Using chrome you can change code on the fly (Developer tools -> Sources tab) and just save it (command + s)
* Use the LiveReload app that actually attaches an extension (that kind of does what you want) <http://livereload.com/>
This may not be the "exact" answer to your question, yet I almost sure one of those will do what you want to do. | ColBeseder correctly brings up Fiddler (http://www.fiddler2.com/fiddler2/version.asp) as a solution to your issue.
Fiddler is perfectly capable of handling and decrypting HTTPS traffic as well - see the documentation on the page for how to configure it.
To directly answer the OP question, you can use the autoresponder feature in Fiddler to hack your production JS for testing.
Enable the autoresponder tab in Fiddler, making sure to leave pass through for unmatched requests checked, entering the URL of the JS files you want to substitute as the pattern. Select the response file from your local filesystem, and go to town!
See <http://yuiblog.com/blog/2008/06/27/fiddler/> (bottom of article is most relevant) for an example. |
3,093,150 | I'm looking for a browser extension (Firefox, Chrome) allowing to replace a Javascript file on a live Web site to do some testing/hacking.
Basically, it should take a URL and load another one instead (locally or on a HTTP development server).
Any idea? | 2010/06/22 | [
"https://Stackoverflow.com/questions/3093150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044/"
]
| I think this is a task for a personal proxy. You can sniff traffic on the proxy and apply rules to modify requests/content | You can intercept and block requests in browsers. For example in Chrome you can use the `beforeload` event check if it's a JS (`event.target` is script tag or `event.url` ends in .js) call `event.preventDefault()` and then load your own script instead.
I'm pretty sure there's a similar way to do this in FF. |
3,093,150 | I'm looking for a browser extension (Firefox, Chrome) allowing to replace a Javascript file on a live Web site to do some testing/hacking.
Basically, it should take a URL and load another one instead (locally or on a HTTP development server).
Any idea? | 2010/06/22 | [
"https://Stackoverflow.com/questions/3093150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044/"
]
| Try <http://www.fiddler2.com/fiddler2/version.asp>
It does that and much more. But it's not a browser extension. | You should probably consider [robohydra](http://dev.opera.com/articles/view/robohydra-a-new-testing-tool-for-client-server-interactions/), since it is specifically developed for your case. They do not support https yet, but they are open to including it in the future. |
44,939,086 | Let say I have 2 forms in my app. let say loginForm and mainForm. In loginForm allows the user to enter his/her username and password then goes to mainForm. From mainForm is I click the back button it will go back to loginForm and now my **issue** is from loginForm if I will click back button it goes again to mainForm without logging in.
What is the best to make this correct?
**loginForm**
```
EditText edtU = (EditText) findViewById (R.id.txtU);
EditText edtP = (EditText) findViewById (R.id.txtP);
Button btnLogin = (Button) findViewById (R.id.btLog);
btnLogin.setOnclickListener(new OnclickListener).......{
if(u.matches("ryan") && p.matches("biugos"){
Intent i = new Intent(getApplicationContext(),mainForm.class);
startActivity(i);
}
}
``` | 2017/07/06 | [
"https://Stackoverflow.com/questions/44939086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| That happend because the Image is a Widget and "the real image" (the picture) is a texture of that Widget, and *by default, the image is centered and fits inside the widget bounding box. If you don’t want that, you can set allow\_stretch to True and keep\_ratio to False.* ([docs](https://kivy.org/docs/api-kivy.uix.image.html#alignment))
For understand that you can add a canvas with a rectangle in the Image Widget like this:
```
Image:
canvas:
Color:
rgba: 1, 1, 1, 0.5
Rectangle:
pos: self.pos
size: self.size
source: 'dog.jpg'
pos_hint: {'left':1, 'top':1}
size_hint: None, None
allow_stretch: True
keep_ratio: False
```
And then you can see why the image doesn't do what you want
[](https://i.stack.imgur.com/xHXER.png)
another pic (*the image(texture) is centered and fits inside the widget*):
[](https://i.stack.imgur.com/UnoAX.png)
One thing you can do is set allow\_stretch: True and keep\_ratio: False
This is the result: (set the size with size\_hint)
[](https://i.stack.imgur.com/oBxMw.png) | Favcau gives one solution above (and thanks), but I have found what I think is more obvious. All it needs is to have the size defined in the kv file.
```
Image:
id: image2
source: 'image_400x90.jpg'
pos_hint: {'left':1, 'top':1}
size_hint: None, None
size: 400, 90
allow_stretch: True
keep_ratio: False
``` |
66,320,285 | I've encountered some unexpected empty lists when using `zip` to transpose the results of `itertools.groupby`. In reality my data is a bunch of objects, but for simplicity let's say my starting data is this list:
```
> a = [1, 1, 1, 2, 1, 3, 3, 2, 1]
```
I want to group the duplicates, so I use `itertools.groupby` (sorting first, because otherwise `groupby` only groups consecutive duplicates):
```
from itertools import groupby
duplicates = groupby(sorted(a))
```
This gives an `itertools.groupby` object which when converted to a list gives
```
[(1, <itertools._grouper object at 0x7fb3fdd86850>), (2, <itertools._grouper object at 0x7fb3fdd91700>), (3, <itertools._grouper object at 0x7fb3fdce7430>)]
```
So far, so good. But now I want to transpose the results so I have a list of the unique values, `[1, 2, 3]`, and a list of the items in each duplicate group, `[<itertools._grouper object ...>, ...]`. For this I used [the solution in this answer](https://stackoverflow.com/a/13635074/2251982) on using zip to "unzip":
```
>>> keys, values = zip(*duplicates)
>>> print(keys)
(1, 2, 3)
>>> print(values)
(<itertools._grouper object at 0x7fb3fdd37940>, <itertools._grouper object at 0x7fb3fddfb040>, <itertools._grouper object at 0x7fb3fddfb250>)
```
But when I try to read the `itertools._grouper` objects, I get a bunch of empty lists:
```
>>> for value in values:
... print(list(value))
...
[]
[]
[]
```
What's going on? Shouldn't each `value` contain the duplicates in the original list, i.e. `(1, 1, 1, 1, 1)`, `(2, 2)` and `(3, 3)`? | 2021/02/22 | [
"https://Stackoverflow.com/questions/66320285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2251982/"
]
| You should avoid using apply whenever possible, but appending items to a list in a cell is tricky and I'm not sure of any way to do so without some sort of iteration. That being said, your operation could be optimized slightly by placing the date conditional in an indexer and then applying on the filtered result. This should provide some noticeable increase in speed:
```
df.loc[df['date']>'2018-10-31','tickers'].apply(lambda x: x.append('LIN'))
```
**Edit:**
some quick comparisons on apply vs. columnwise operations.
For this example I just used a simple operation where the values in column 'A' were being incremented by 1. We'll compare the two following methods of achieving the aforementioned result:
```
apply_op = """
df['A']=df.apply(lambda row: row['A']+1,axis=1)
"""
series_op = """
df['A']=df['A']+1
"""
```
First we'll run some speed tests to see how quickly each performs.
```
df:
A B C D
0 1 2 9 6
1 5 8 1 9
2 6 8 0 1
3 6 1 6 8
4 9 0 1 4
.. .. .. .. ..
995 1 3 8 9
996 1 2 3 3
997 2 2 9 1
998 4 9 2 5
999 10 2 0 3
[1000 rows x 4 columns]
Apply op:
[in]:
df['A']=df.apply(lambda row: row['A']+1,axis=1)
[out]:
A B C D
0 1 2 9 6
1 5 8 1 9
2 6 8 0 1
3 6 1 6 8
4 9 0 1 4
Average execution time:0.0226791306 ms
Series op:
[in]:
df['A']=df['A']+1
[out]:
A B C D
0 1 2 9 6
1 5 8 1 9
2 6 8 0 1
3 6 1 6 8
4 9 0 1 4
Average execution time:0.0005004938999999986 ms
```
The series operation has ~4000% increase in speed.
Now lets take a look under the hood and see what instructions are compiled for each operation:
```
>>> dis.dis(apply_op)
2 0 LOAD_NAME 0 (df)
2 LOAD_ATTR 1 (apply)
4 LOAD_CONST 0 (<code object <lambda> at 0x090B56A8, file "<dis>", line 2>)
6 LOAD_CONST 1 ('<lambda>')
8 MAKE_FUNCTION 0
10 LOAD_CONST 2 (1)
12 LOAD_CONST 3 (('axis',))
14 CALL_FUNCTION_KW 2
16 LOAD_NAME 0 (df)
18 LOAD_CONST 4 ('A')
20 STORE_SUBSCR
22 LOAD_CONST 5 (None)
24 RETURN_VALUE
Disassembly of <code object <lambda> at 0x090B56A8, file "<dis>", line 2>:
2 0 LOAD_FAST 0 (row)
2 LOAD_CONST 1 ('A')
4 BINARY_SUBSCR
6 LOAD_CONST 2 (1)
8 BINARY_ADD
10 RETURN_VALUE
>>> dis.dis(series_op)
2 0 LOAD_NAME 0 (df)
2 LOAD_CONST 0 ('A')
4 BINARY_SUBSCR
6 LOAD_CONST 1 (1)
8 BINARY_ADD
10 LOAD_NAME 0 (df)
12 LOAD_CONST 0 ('A')
14 STORE_SUBSCR
16 LOAD_CONST 2 (None)
18 RETURN_VALUE
```
It's been a while since I've had to write any assembly, but I'll try to quickly explain what we see above. The first output of apply\_op shows the subroutine of the apply function that is called for every single row in the df. For each row, the row, column ('A'), and constant (1) must be retrieved to perform the operation.
In the second output for series\_op, we can see that the entire column "A" is loaded once as a single constant. This series operation only performs the addition operation twice; once for the the entire array except for the last item, and one last (second) time for the last item of the array.
For a little bit more on array vectorization: (btw, I rarely find a use case for parallelization of dataframes that makes sense.)
[Vectorization and parallelization in Python with Numpy and Pandas](https://datascience.blog.wzb.eu/2018/02/02/vectorization-and-parallelization-in-python-with-numpy-and-pandas/) | This code is computationally more efficient (a little bit) although I don't know if I'd call it better. Your code would work fine and be easier to read.
You can make this even more efficient if you didn't uses lists within the pandas rows. (I could think of a more efficient way to append than using a lambda.)
```
import numpy as np
df['tickers'] = np.where(df['date']>pd.to_datetime('2018-10-31'),
df['tickers'],
df['tickers'].apply(lambda x: x = ['LIN'])
```
Also, be careful about the comparison for the date. I used the same date comparison as the example assuming you know what you are doing, but you are comparing text. For my comparison to work in my sample code, I needed to add `pd.to_datetime`. |
17,366,978 | I need a way to convert special characters like this:
`Helloæ`
To normal characters. So this word would end up being `Helloae`. So far I have tried `HttpUtility.Decode`, or a method that would convert UTF8 to win1252, but nothing worked. Is there something simple and generic that would do this job?
Thank you.
**EDIT**
I have tried implementing those two methods using posts here on OC. Here's the methods:
```
public static string ConvertUTF8ToWin1252(string _source)
{
Encoding utf8 = new UTF8Encoding();
Encoding win1252 = Encoding.GetEncoding(1252);
byte[] input = _source.ToUTF8ByteArray();
byte[] output = Encoding.Convert(utf8, win1252, input);
return win1252.GetString(output);
}
// It should be noted that this method is expecting UTF-8 input only,
// so you probably should give it a more fitting name.
private static byte[] ToUTF8ByteArray(this string _str)
{
Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(_str);
}
```
But it did not worked. The string remains the same way. | 2013/06/28 | [
"https://Stackoverflow.com/questions/17366978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2021863/"
]
| See: [Does .NET transliteration library exists?](https://stackoverflow.com/questions/10027001/does-net-transliteration-library-exists)
[UnidecodeSharpFork](https://bitbucket.org/DimaStefantsov/unidecodesharpfork)
Usage:
```
var result = "Helloæ".Unidecode();
Console.WriteLine(result) // Prints Helloae
``` | There is no direct mapping between `æ` and `ae` they are completely different unicode code points. If you need to do this you'll most likely need to write a function that maps the offending code points to the strings that you desire.
Per the comments you may need to take a two stage approach to this:
1. Remove the diacritics and combining characters per the link to the possible duplicate
2. Map any characters left that are not combining to alternate strings
```
switch(badChar){
case 'æ':
return "ae";
case 'ø':
return "oe";
// and so on
}
``` |
315,796 | I intend to setup a samba share server that all user can write files to but they can not delete files was put in that folder.
Which configuration is suitable for me!
Thanks in advanced! | 2011/09/27 | [
"https://serverfault.com/questions/315796",
"https://serverfault.com",
"https://serverfault.com/users/9401/"
]
| The user needs to have the linux file system rwx permissions on the directory the file is in, to be able to delete files in the directory.
You can achieve this by default in a few different ways, for new files one method is the use of default create masks so all new files and folders will have the correct linux file system permissions. | As far as I know it isn't done with samba, but with linux. You should assign the sticky flag to the main share directory with chmod. For example, if you're sharing /home/foo you should execute "chmod +t /home/foo/".
Also I suggest to use the linux ACL system or the default creation mask in samba configuration to propagate automatically this behaviour to subdirectories. |
4,018,268 | I am struggling with a concept of finding the **radius** in the shell method of finding the volume of the solid when revolved around a line other than the axis. Maybe the issue here is that I am looking for a "rule" instead of actually visualizing the problem. It was my understanding that when revolving around a line other than the axis a formula could be used as follows: (*this example uses revolution about a vertical line other than the $y$ axis*)
the radius would be $|verticalvalue|$ $+/-$ $x$. Use $+$ if the region of revolution is to the **right** of the line and use $-$ if the region is to the **left**.
I ***thought*** I had worked many problems using this concept and gotten the correct answer. However, doesn't work in this problem:
Use the method of cylindrical shells to find the volume generated by rotating $y=x^2$, $y=0$, $x=1$, $x=2$ about the line $x=1$.
My integral, using my above "***concept***" was to form the following integral:
$V=2\pi\int(1+x)(x^2) dx$ evaluated from lower limit of 1 to upper limit of 2. I used the absolute value of $1$ PLUS (since the region of revolution is to the right of the vertical line of revolution.
This does not produce the book answer and the book used $x-1$ for the radius instead of $x+1$, obviously producing very different results.
My question: is there a ***rule*** for writing the radius? Why didn't my rule work? | 2021/02/08 | [
"https://math.stackexchange.com/questions/4018268",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/163862/"
]
| You would only "use the absolute value of 1 plus the x" if the region of rotation was to the right of the vertical line of revolution AND the left boundary of the region of rotation were to the left of the y-axis. Perhaps most of the problems you did in the past were this case.
---
There are rules for these types of problems. If you are rotating about a vertical line, and the axis of rotation is the left boundary, you use $x-h$. But if you're rotating about the right boundary, you use $h-x$.
As for your problem, it is usually better to draw a picture. I don't know anyone who doesn't at least visualize these types of find-the-volume-of-rotation problems.
[](https://i.stack.imgur.com/2r3Gp.png)
Since $1\le 1< 2$, use $\int\_1^2 (x-1)f(x)dx$. You get
$$2\pi\int\_1^2(x-1)x^2dx$$
However if you were to rotate it around the line h=2, not shown, you get
$$2\pi\int\_1^2(2-x)x^2dx$$
Note that you would get a larger volume for the first rotation (h=1) because the taller part of it has to rotate more, covering more volume, but for the second rotation (h=2), the larger part is in the "center" and creates less volume. | " Maybe the issue here is that I am looking for a "rule" instead of actually visualizing the problem". I am not sure if that is a good idea. However, what you CAN do is, perform a horizontal translation (a shift of $1$ units to the left) on all functions in question. So "Use the method of cylindrical shells to find the volume generated by rotating $y=x^2$,$ y=0$, $x=1$, $x=2$ about the line $x=1$, now becomes "rotating the region formed by$y=(x+1)^2$, $y=0$, $x=0$, $x=1$ about $x=0$. This way you can now apply the "standard" formulas for cylindrical shells since the axis of rotation is now a coordinate axis. I would still make a graph of the situation, try to understand why this works |
3,425,319 | Prove the divisibility test by $7,11,13$ for numbers more than six digits
---
**Attempt:**
We know that $7\cdot 11 \cdot 13 = 1001$. The for a six-digit number, for example, $120544$, we write it as
$$ 120544 = 120120 + 424 = 120\cdot1001 + 424 $$
thus we just check the divisibility of $424$ by $7,11,13$.
Know for a number with more than six digits, for example: $270060340$,
$$270060340 = 270270270 - 209930$$
$$ = 270 \cdot (1001001) - 209930 $$
$$ = 270 \cdot (1001000) + (270 - 209930) =270 \cdot (1001000) - 209660$$
so we check the divisibility of $209660 = 209209 + 451$, or just $451$.
But the test states that: for $270060340$, we group three digits from the right:
$$ 270, 60, 340$$
then check divisibility of $340+270 - (60)$.
How to prove this? | 2019/11/07 | [
"https://math.stackexchange.com/questions/3425319",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/97835/"
]
| It's the [radix$+1$ divisibility test](https://math.stackexchange.com/a/16015/242) for radix $10^3,\,$ i.e. the analog of casting out $11's$ in radix $10,\,$ viz.
$\!\!\!\begin{align}\bmod 10^{\large 3}\!+\!1\!:\,\ \color{#0a0}{10^{\large 3}}\equiv \color{#c00}{\bf -1}\, \ \Rightarrow\!\!\!\! &\ \ \ \ \ \ \overbrace{d\_0 + d\_1 \ \color{#0a0}{10^{\large 3}} +\, d\_2(\color{#0a0}{10^{\large 3}})^{\large 2}\! + d\_3(\color{#0a0}{10^{\large 3}})^{\large 3}+\,\cdots }^{\!\!\!\!\!\!\!\textstyle\text{integer in radix $\color{#0a0}{10^{\large 3}}$ with digits $\,d\_i$}} \\[.3em]
&\equiv\, d\_0\!+d\_1(\color{#c00}{\bf -1})\!+d\_2(\color{#c00}{\bf -1})^{\large 2}\! + d\_3(\color{#c00}{\bf -1})^{\large 3} +\,\cdots \\[.3em]
&\equiv\, d\_0\ \ \color{#c00}{\bf -}\ \ d\_1\ \ +\ \ d\_2\ \ \color{#c00}{\bf -}\ \ d\_3\ +\, \cdots\\[.2em]
&\equiv\, \color{#c00}{\text {alternating}}\text{ digit sum}\end{align}$
where we employed the [Congruence Sum & Product Rules (or Polynomial Rule)](https://math.stackexchange.com/a/879262/242)
$\!\begin{align}\text{E.g. in your 2nd example: }\ \ \ \ \ \ \ &\overbrace{270\,,\,060\,,\,340}^{\textstyle d\_2,\ \ d\_1,\ \ d\_0}\\[.2em]
\equiv\ &270\! -\! 060\! +\! 340\, \equiv\, 550\!\pmod{\!1001}\end{align}$ | $1001$ divides $999,999$ and $999,999 = 1,000,000 - 1$
$270,060,340 = (270,000,000 - 27) + (60,000 + 60) + 340 + 27 -60$
The first two terms are divisible by $1001$ (and hence 7,11, and 13) |
3,425,319 | Prove the divisibility test by $7,11,13$ for numbers more than six digits
---
**Attempt:**
We know that $7\cdot 11 \cdot 13 = 1001$. The for a six-digit number, for example, $120544$, we write it as
$$ 120544 = 120120 + 424 = 120\cdot1001 + 424 $$
thus we just check the divisibility of $424$ by $7,11,13$.
Know for a number with more than six digits, for example: $270060340$,
$$270060340 = 270270270 - 209930$$
$$ = 270 \cdot (1001001) - 209930 $$
$$ = 270 \cdot (1001000) + (270 - 209930) =270 \cdot (1001000) - 209660$$
so we check the divisibility of $209660 = 209209 + 451$, or just $451$.
But the test states that: for $270060340$, we group three digits from the right:
$$ 270, 60, 340$$
then check divisibility of $340+270 - (60)$.
How to prove this? | 2019/11/07 | [
"https://math.stackexchange.com/questions/3425319",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/97835/"
]
| It's the [radix$+1$ divisibility test](https://math.stackexchange.com/a/16015/242) for radix $10^3,\,$ i.e. the analog of casting out $11's$ in radix $10,\,$ viz.
$\!\!\!\begin{align}\bmod 10^{\large 3}\!+\!1\!:\,\ \color{#0a0}{10^{\large 3}}\equiv \color{#c00}{\bf -1}\, \ \Rightarrow\!\!\!\! &\ \ \ \ \ \ \overbrace{d\_0 + d\_1 \ \color{#0a0}{10^{\large 3}} +\, d\_2(\color{#0a0}{10^{\large 3}})^{\large 2}\! + d\_3(\color{#0a0}{10^{\large 3}})^{\large 3}+\,\cdots }^{\!\!\!\!\!\!\!\textstyle\text{integer in radix $\color{#0a0}{10^{\large 3}}$ with digits $\,d\_i$}} \\[.3em]
&\equiv\, d\_0\!+d\_1(\color{#c00}{\bf -1})\!+d\_2(\color{#c00}{\bf -1})^{\large 2}\! + d\_3(\color{#c00}{\bf -1})^{\large 3} +\,\cdots \\[.3em]
&\equiv\, d\_0\ \ \color{#c00}{\bf -}\ \ d\_1\ \ +\ \ d\_2\ \ \color{#c00}{\bf -}\ \ d\_3\ +\, \cdots\\[.2em]
&\equiv\, \color{#c00}{\text {alternating}}\text{ digit sum}\end{align}$
where we employed the [Congruence Sum & Product Rules (or Polynomial Rule)](https://math.stackexchange.com/a/879262/242)
$\!\begin{align}\text{E.g. in your 2nd example: }\ \ \ \ \ \ \ &\overbrace{270\,,\,060\,,\,340}^{\textstyle d\_2,\ \ d\_1,\ \ d\_0}\\[.2em]
\equiv\ &270\! -\! 060\! +\! 340\, \equiv\, 550\!\pmod{\!1001}\end{align}$ | For 9-digit number: $abcdefghi$,
$$ abcdefghi = abc000000 + defghi = abc000000 + def \cdot 1001 - def + ghi $$
so we check divisibility of
$$ abc000000 - def + ghi = abc \cdot 1001000 - abc000 - def + ghi$$
so we cehck divisibility of
$$ -abc000 - def + ghi = -(abc \cdot 1001 - abc) - def + ghi$$
in the end we only check $abc + ghi - def$.
If 12-digit number:
$$ a\_{1} a\_{2} ... a\_{11}a\_{12} = a\_{1} a\_{2} a\_{3} 000000000 + \underbrace{a\_{4} ... a\_{12}}\_{9-digit}$$
so we check the divisibility of
$$ a\_{1} a\_{2} a\_{3} 000000000 + ( a\_{10}a\_{11}a\_{12} + a\_{4} a\_{5}a\_{6} - a\_{7}a\_{8}a\_{9}) $$
or just
$$ = (a\_{10}a\_{11}a\_{12} + a\_{4} a\_{5}a\_{6} - a\_{7}a\_{8}a\_{9} - a{1} a\_{2} a\_{3}) $$ |
2,716,498 | >
> Does a closed form of the following sum exist?$$\sum\_{n=0}^\infty \frac{1}{{2}^{2n}}\frac{\binom{2n}{n}}{{(2n+1)}^2}$$
>
>
> | 2018/03/31 | [
"https://math.stackexchange.com/questions/2716498",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/534404/"
]
| Yes. Starting with
$$
\frac1{\sqrt{1-4x^2}} = \sum\_{n=0}^\infty \binom{2n}n x^{2n},
$$
you can perform the following steps to obtain your sum:
* multiply by $x$
* integrate
* divide by $x$
* integrate again
* divide by $x^2$
* set $x=\frac12$
Mathematica says that the ultimate answer is $\frac{\pi\log4}4$. | $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
\newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
\newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
\newcommand{\dd}{\mathrm{d}}
\newcommand{\ds}[1]{\displaystyle{#1}}
\newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
\newcommand{\ic}{\mathrm{i}}
\newcommand{\mc}[1]{\mathcal{#1}}
\newcommand{\mrm}[1]{\mathrm{#1}}
\newcommand{\pars}[1]{\left(\,{#1}\,\right)}
\newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
\newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
\newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
\newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
>
> [Note that](https://math.stackexchange.com/a/1991085/85343)
> $\ds{{2n \choose n} = {-1/2 \choose n}\pars{-4}^{n}}$.
>
>
>
\begin{align}
\sum\_{n = 0}^{\infty}{1 \over 2^{2n}}{{2n \choose n} \over \pars{2n + 1}^{2}} & =
\sum\_{n = 0}^{\infty}{-1/2 \choose n}\pars{-1}^{n}\
\overbrace{\bracks{-\int\_{0}^{1}\ln\pars{x}x^{2n}\,\dd x}}
^{\ds{1 \over \pars{2n + 1}^{2}}}
\\[5mm] & =
-\int\_{0}^{1}\ln\pars{x}\sum\_{n = 0}^{\infty}{-1/2 \choose n}\pars{-x^{2}}^{n}
\,\dd x =
-\int\_{0}^{1}\ln\pars{x}\pars{1 - x^{2}}^{-1/2}\,\dd x
\\[5mm] & =
-\,{1 \over 4}\int\_{0}^{1}x^{-1/2}\ln\pars{x}\pars{1 - x}^{-1/2}\,\dd x =
\left. -\,{1 \over 4}\partiald{}{\nu}\int\_{0}^{1}x^{\nu - 1/2}
\pars{1 - x}^{-1/2}\,\dd x\,\right\vert\_{\ \nu\ =\ 0}
\\[5mm] & =
\left. -\,{1 \over 4}\partiald{}{\nu}
{\Gamma\pars{\nu + 1/2}\Gamma\pars{1/2} \over \Gamma\pars{\nu + 1}}\right\vert\_{\ \nu\ =\ 0}
\\[5mm] & =
\left. -\,{\root{\pi} \over 4}\partiald{}{\nu}
{\Gamma\pars{1/2} + \Gamma\pars{1/2}\Psi\pars{1/2}\nu
\over 1 - \gamma\nu}\,\right\vert\_{\ \nu\ =\ 0}
\\[5mm] & =
\left. -\,{\pi \over 4}\partiald{}{\nu}
\bracks{1 + \Psi\pars{1 \over 2}\nu}\pars{1 + \gamma\nu}
\right\vert\_{\ \nu\ =\ 0}
\\[5mm] & =
-\,{\pi \over 4}\ \overbrace{\bracks{\Psi\pars{1 \over 2} + \gamma}}
^{\ds{-2\ln\pars{2}}}\ = \bbx{{1 \over 2}\,\ln\pars{2}\pi} \approx 1.0888
\end{align} |
155,797 | Given a list of positive integers determine if there is an element that is either greater than its two neighbors or less than its two neighbors (a "bump"). To be clear a bump can never be the first or last item of the list because they only have one neighbor.
Your program should output one of two consistent values each corresponding to either a list with no bumps or a list with bumps. What the values are is unimportant you may choose them yourself.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
Test cases
----------
```
[] -> False
[1] -> False
[1,2] -> False
[1,2,1] -> True
[1,2,2] -> False
[1,2,3] -> False
[1,2,2,1] -> False
[1,2,2,3] -> False
[1,2,1,2] -> True
[1,3,2] -> True
[3,1,2] -> True
[2,2,2] -> False
``` | 2018/02/14 | [
"https://codegolf.stackexchange.com/questions/155797",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/56656/"
]
| [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
=========================================================
```
IṠIỊẠ
```
Returns **0** if there's a bump, **1** if not.
[Try it online!](https://tio.run/##y0rNyan8/9/z4c4Fng93dz3cteD/4fZHTWsi//@PjtVRiDYEEzpGUEoHxkeIGMNFkCQRonC9xhCGkY4BUB0A "Jelly – Try It Online")
### How it works
```
IṠIỊẠ Main link. Argument: A (integer array)
I Increments; take all forward differences of A.
Ṡ Take the signs.
The signs indicate whether the array is increasing (1), decreasing (-1), or
constant at the corresponding point. A 1 followed by a -1 indicates a local
maximum, a -1 followed by a 1 a local minimum.
I Increments; take the forward differences again.
Note that 1 - (-1) = 2 and (-1) - 1 = -2. All other seven combinations of
signs map to -1, 0, or 1.
Ị Insignificant; map each difference d to (-1 ≤ d ≤ 1).
Ạ All; return 1 if all differences are insignificant, 0 if not.
``` | [APL (Dyalog)](https://www.dyalog.com/), ~~15~~ ~~19~~ 20 bytes
===============================================================
*2 bytes saved thanks to @EriktheOutgolfer*
```apl
{2>≢⍵:0⋄2∊|2-/×2-/⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqI7tHnYse9W61MnjU3WL0qKOrxkhX//B0IAEUrAUqUnjUu4YrTcGQi0vdVp0LxFIwgpBw2hjGB6qCsYyR1cPFYXqNwbSRggGSDiAJAA "APL (Dyalog Unicode) – Try It Online")
**1** for bump, **0** for no bump. |
155,797 | Given a list of positive integers determine if there is an element that is either greater than its two neighbors or less than its two neighbors (a "bump"). To be clear a bump can never be the first or last item of the list because they only have one neighbor.
Your program should output one of two consistent values each corresponding to either a list with no bumps or a list with bumps. What the values are is unimportant you may choose them yourself.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
Test cases
----------
```
[] -> False
[1] -> False
[1,2] -> False
[1,2,1] -> True
[1,2,2] -> False
[1,2,3] -> False
[1,2,2,1] -> False
[1,2,2,3] -> False
[1,2,1,2] -> True
[1,3,2] -> True
[3,1,2] -> True
[2,2,2] -> False
``` | 2018/02/14 | [
"https://codegolf.stackexchange.com/questions/155797",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/56656/"
]
| [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
==================================================================================
```
MatchQ[{___,x_,y_,z_,___}/;x<y>z||x>y<z]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@983sSQ5IzC6Oj4@XqciXqcyXqcqXgfIqdW3rrCptKuqqamwq7Spiv0fUJSZVxKtrKOgpKBrp6Cko5AWrRwbq6CmoO@gUF1dq6NQbQgmdBSMYLSOgiGCiSRqjCSKqgZFDskoYyjTGCFqBDW19j8A "Wolfram Language (Mathematica) – Try It Online") | [Python 2](https://docs.python.org/2/), 60 bytes
================================================
```python
lambda l:any(p>c<n or p<c>n for p,c,n in zip(l,l[1:],l[2:]))
```
[Try it online!](https://tio.run/##HcY7DoAgEAXAq7wSkm3AjqAXUQrEEElw3RgbvTx@msnIda4725b7qdW4zUtEdZEvJUPyjP2A@DQw8jdKxCiMu4iqVEfjwqt1QesmR@ETWY2GYAndrwm6PQ "Python 2 – Try It Online")
Pretty much the same thing, thought it would be shorter though...
[Python 2](https://docs.python.org/2/), 63 bytes
================================================
```python
f=lambda l:l[3:]and(l[0]>l[1]<l[2]or l[0]<l[1]>l[2]or f(l[1:]))
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIccqJ9rYKjYxL0UjJ9og1i4n2jDWJifaKDa/SAEkYAMSsIMKpAHVGFrFamr@LyjKzCsB8qMNdRSMdBSMwaRhrOZ/AA "Python 2 – Try It Online") |
155,797 | Given a list of positive integers determine if there is an element that is either greater than its two neighbors or less than its two neighbors (a "bump"). To be clear a bump can never be the first or last item of the list because they only have one neighbor.
Your program should output one of two consistent values each corresponding to either a list with no bumps or a list with bumps. What the values are is unimportant you may choose them yourself.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
Test cases
----------
```
[] -> False
[1] -> False
[1,2] -> False
[1,2,1] -> True
[1,2,2] -> False
[1,2,3] -> False
[1,2,2,1] -> False
[1,2,2,3] -> False
[1,2,1,2] -> True
[1,3,2] -> True
[3,1,2] -> True
[2,2,2] -> False
``` | 2018/02/14 | [
"https://codegolf.stackexchange.com/questions/155797",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/56656/"
]
| [Perl 6](http://perl6.org/), 39 bytes
=====================================
```
{so~(.[1..*]Zcmp$_)~~/'re L'|'s M'/}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/uji/TkMv2lBPTys2Kjm3QCVes65OX70oVcFHvUa9WMFXXb/2f3FipYKSSryCrZ1CdZqCSnytkkJafpFCdKyOgo2hHYhQMIJSCjA@QsQYLoIkiRCF6zWGMIwUDIDq/gMA "Perl 6 – Try It Online")
`$_` is the list argument to this anonymous function. `.[1..*]` is the same list, but with the first element dropped. `Zcmp` zips the two lists together with the `cmp` operator, resulting in a list of `Order` values. For example, for an input list `1, 2, 2, 2, 1` this would result in the list `More, Same, Same, Less`.
Now we just need to know whether that list contains two adjacent elements `More, Less` or `Less, More`. The trick I used is to convert the list to a space-delimited string with `~`, then test whether it contains either substring `re L` or `s M`. (The first one can't be just `e L` because `Same` also ends with an "e".)
The smart match operator returns either a `Match` object (if the match succeeded) or `Nil` (if it didn't), so `so` converts whatever it is into a boolean value. | [Julia 0.6](http://julialang.org/), 57 56 bytes
===============================================
```julia
l->any(p>c<n||p<c>n for(p,c,n)=zip(l,l[2:end],l[3:end]))
```
Basically just totallyhuman's python answer. -1 byte from user71546
[Try it online!](https://tio.run/##yyrNyUw0@59mm5Sanpn3P0fXLjGvUqPALtkmr6amwCbZLk8hLb9Io0AnWSdP07Yqs0AjRycn2sgqNS8lFsgwBjM0Nf8DKa7S4sy8dAWnxOJUvZDU4hIuhxIgWZxaoqAEYigkAyWKlRTAFkHkFNI0og11jHQMYzXRBHSMUIXMzVHEFGGCQISi0kjHAMk0RahxRmhiQA7Qvf8B "Julia 0.6 – Try It Online")
[Julia 0.6](http://julialang.org/), 39 bytes
============================================
```julia
f(x,y,z,a...)=x>y<z||x<y>z||f(y,z,a...)
```
Lispy recursion style, aka Dennis's python answer. Returns `true` when a bump exists, otherwise throws an error. This should maybe be 42 bytes since you have to splat it when calling. Eg for `a=[1,2,1]` you call as `f(a...)`. `f(a)=f(a...)` would remove that need, but is longer. I need to get better a recursion, and I don't really like writing code that throws an error.
[Try it online!](https://tio.run/##yyrNyUw0@/8/TaNCp1KnSidRT09P07bCrtKmqqamwqbSDkilacBl/pcWZ@alKzglFqfqhaQWl3A5lADJ4tQSBSUQQyEZKFGspJCUmp6ZB5FTSNOINtQx0jGMBelHE9MxwhA1N0cTji/JKMovL1bwTS3JyE9xLSrKL4KrBCJ0E4x0DFDswqndCM1ROBRCVKTmpfwHAA "Julia 0.6 – Try It Online") |
155,797 | Given a list of positive integers determine if there is an element that is either greater than its two neighbors or less than its two neighbors (a "bump"). To be clear a bump can never be the first or last item of the list because they only have one neighbor.
Your program should output one of two consistent values each corresponding to either a list with no bumps or a list with bumps. What the values are is unimportant you may choose them yourself.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
Test cases
----------
```
[] -> False
[1] -> False
[1,2] -> False
[1,2,1] -> True
[1,2,2] -> False
[1,2,3] -> False
[1,2,2,1] -> False
[1,2,2,3] -> False
[1,2,1,2] -> True
[1,3,2] -> True
[3,1,2] -> True
[2,2,2] -> False
``` | 2018/02/14 | [
"https://codegolf.stackexchange.com/questions/155797",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/56656/"
]
| [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
=========================================================
```
IṠIỊẠ
```
Returns **0** if there's a bump, **1** if not.
[Try it online!](https://tio.run/##y0rNyan8/9/z4c4Fng93dz3cteD/4fZHTWsi//@PjtVRiDYEEzpGUEoHxkeIGMNFkCQRonC9xhCGkY4BUB0A "Jelly – Try It Online")
### How it works
```
IṠIỊẠ Main link. Argument: A (integer array)
I Increments; take all forward differences of A.
Ṡ Take the signs.
The signs indicate whether the array is increasing (1), decreasing (-1), or
constant at the corresponding point. A 1 followed by a -1 indicates a local
maximum, a -1 followed by a 1 a local minimum.
I Increments; take the forward differences again.
Note that 1 - (-1) = 2 and (-1) - 1 = -2. All other seven combinations of
signs map to -1, 0, or 1.
Ị Insignificant; map each difference d to (-1 ≤ d ≤ 1).
Ạ All; return 1 if all differences are insignificant, 0 if not.
``` | [Perl 5](https://www.perl.org/), 54 + 2 (`-pa`) = 56 bytes
==========================================================
```perl
map$\|=$F[$_-1]!=(sort{$a-$b}@F[$_-2..$_])[1],2..$#F}{
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUAlpsZWxS1aJV7XMFbRVqM4v6ikWiVRVyWp1gEsaqSnpxIfqxltGKsDYiq71Vb//2@oYASEBv/yC0oy8/OK/@v6muoZGBr81y1IBAA "Perl 5 – Try It Online") |
155,797 | Given a list of positive integers determine if there is an element that is either greater than its two neighbors or less than its two neighbors (a "bump"). To be clear a bump can never be the first or last item of the list because they only have one neighbor.
Your program should output one of two consistent values each corresponding to either a list with no bumps or a list with bumps. What the values are is unimportant you may choose them yourself.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
Test cases
----------
```
[] -> False
[1] -> False
[1,2] -> False
[1,2,1] -> True
[1,2,2] -> False
[1,2,3] -> False
[1,2,2,1] -> False
[1,2,2,3] -> False
[1,2,1,2] -> True
[1,3,2] -> True
[3,1,2] -> True
[2,2,2] -> False
``` | 2018/02/14 | [
"https://codegolf.stackexchange.com/questions/155797",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/56656/"
]
| [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~37~~ 36 bytes
=========================================================================================
```
FreeQ[(d=Differences)@Sign@d@#,-2|2]&
```
Gives the opposite of the test case answers (False and True reversed). Prepend a `!` to switch to the normal form.
OR
```
Abs@(d=Differences)@Sign@d@#~FreeQ~2&
```
Also reversed output, so replace `FreeQ` with `MatchQ` for normal form.
Explanation: Take the sign of the differences of the sequence. Iff the resulting sequence includes {1,-1} or {-1,1} there is a bump. The absolute value the differences of {1,-1} or {-1,1} is 2 in either case.
Shave off another byte by squaring the final list instead of taking the absolute value:
```
FreeQ[(d=Differences)@Sign@d@#^2,4]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7360oNTUwWiPF1iUzLS21KDUvObVY0yE4Mz3PIcVBWUfXqMYoVu1/QFFmXkl0mr5DdXWtTrUhCOsYQUgdKA/ON4bxETJwMZguYzBtDOUbgXXXxv4HAA "Wolfram Language (Mathematica) – Try It Online") | [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 43 bytes
======================================================================================================================
```
.+
$*
1`(1+)1¶\1¶1\1|¶(1+)(?<!\2¶\2)¶(?!\2)
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLMEHDUFvT8NC2GCA2jDGsObQNJKBhb6MYYwQUNdIECtgD2Zr//xtyGXEZAgA "Retina 0.8.2 – Try It Online") Takes input on separate lines and outputs 0 or 1. Explanation:
```
.+
$*
```
Convert to unary.
```
1` |
```
Count at most one matching regex.
```
(1+)1¶\1¶1\1
```
Match a number that is surrounded by greater numbers on both sides.
```
¶(1+)(?<!\2¶\2)¶(?!\2)
```
Match a number that is not surrounded by greater or equal numbers on either side, i.e. both are less. |
155,797 | Given a list of positive integers determine if there is an element that is either greater than its two neighbors or less than its two neighbors (a "bump"). To be clear a bump can never be the first or last item of the list because they only have one neighbor.
Your program should output one of two consistent values each corresponding to either a list with no bumps or a list with bumps. What the values are is unimportant you may choose them yourself.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
Test cases
----------
```
[] -> False
[1] -> False
[1,2] -> False
[1,2,1] -> True
[1,2,2] -> False
[1,2,3] -> False
[1,2,2,1] -> False
[1,2,2,3] -> False
[1,2,1,2] -> True
[1,3,2] -> True
[3,1,2] -> True
[2,2,2] -> False
``` | 2018/02/14 | [
"https://codegolf.stackexchange.com/questions/155797",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/56656/"
]
| [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
==========================================================
```
s₃.¬≤₁∧¬≥₁
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/hRU7PeoTWPOpc8amp81LEcxFwKZP7/H22oY6QDxLEA "Brachylog – Try It Online")
Succeeds (`true.`) if there is a bump, and fails (`false.`) if there is no bump.
### Explanation
This is fairly readable already:
```
s₃. There is a substring of the input…
.¬≤₁ …which is not non-decreasing…
∧ …and…
¬≥₁ …which is not non-increasing
``` | [Husk](https://github.com/barbuz/Husk), 9 bytes
===============================================
```
▼mεẊ-Ẋo±-
```
[Try it online!](https://tio.run/##yygtzv7//9G0Pbnntj7c1aULxPmHNur@//8/2kgHCGMB "Husk – Try It Online")
Uses Dennis's algorithm. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.