text:
Q: Configure number of cell in a section of static UITableView I have a static table view with 7 sections, but I want section 1 to be prototype, so I did this to configure the row:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return 1;
    } else {
        return [super tableView:tableView numberOfRowsInSection:section];
    }
}

But everything went fine until this part:
return 1;

The program crashes after this line. Is there a way to fix this or a workaround that can also achieve this. Thanks.
P.S. Here is the call stack:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'
*** First throw call stack:
(
0   CoreFoundation                      0x0000000105f6cf45 __exceptionPreprocess + 165
1   libobjc.A.dylib                     0x00000001059e6deb objc_exception_throw + 48
2   CoreFoundation                      0x0000000105f1b975 -[__NSArray0 objectAtIndex:] + 101
3   UIKit                               0x0000000106a263e8 -[UITableViewDataSource tableView:heightForRowAtIndexPath:] + 181
4   UIKit                               0x00000001066f622a -[UITableViewController tableView:heightForRowAtIndexPath:] + 63
5   UIKit                               0x000000010666b5cf __66-[UISectionRowData refreshWithSection:tableView:tableViewRowData:]_block_invoke + 240
6   UIKit                               0x000000010666ac5f -[UISectionRowData refreshWithSection:tableView:tableViewRowData:] + 4876
7   UIKit                               0x000000010666d2a7 -[UITableViewRowData _ensureSectionOffsetIsValidForSection:] + 279
8   UIKit                               0x00000001066708bb -[UITableViewRowData rectForFooterInSection:heightCanBeGuessed:] + 423
9   UIKit                               0x00000001066709e8 -[UITableViewRowData heightForTable] + 62
10  UIKit                               0x000000010643c6a2 -[UITableView _updateContentSize] + 374
11  UIKit                               0x0000000106462f19 -[UITableView _rebuildGeometry] + 40
12  UIKit                               0x000000010646124e -[UITableView setLayoutMargins:] + 389
13  UIKit                               0x0000000106461090 -[UITableView _setDefaultLayoutMargins:] + 134
14  UIKit                               0x00000001064a2420 -[UIViewController _setContentOverlayInsets:] + 692
15  UIKit                               0x00000001064a2e43 -[UIViewController _updateContentOverlayInsetsFromParentIfNecessary] + 2067
16  UIKit                               0x00000001064a249d -[UIViewController _updateContentOverlayInsetsForSelfAndChildren] + 101
17  UIKit                               0x00000001064ae199 -[UIViewController _updateLayoutForStatusBarAndInterfaceOrientation] + 972
18  UIKit                               0x00000001064b3c0b -[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:] + 1242
19  UIKit                               0x00000001063c7b45 -[UIView(Internal) _didMoveFromWindow:toWindow:] + 1613
20  UIKit                               0x00000001063dc5ba -[UIScrollView _didMoveFromWindow:toWindow:] + 85
21  UIKit                               0x00000001063c7856 -[UIView(Internal) _didMoveFromWindow:toWindow:] + 862
22  UIKit                               0x00000001063bce2c __45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke + 155
23  UIKit                               0x00000001063bcd2b -[UIView(Hierarchy) _postMovedFromSuperview:] + 544
24  UIKit                               0x00000001063ca7e7 -[UIView(Internal) _addSubview:positioned:relativeTo:] + 1967
25  UIKit                               0x000000010678b0ad -[UINavigationTransitionView transition:fromView:toView:] + 672
26  UIKit                               0x00000001064f1791 -[UINavigationController _startTransition:fromViewController:toViewController:] + 3291
27  UIKit                               0x00000001064f1d8d -[UINavigationController _startDeferredTransitionIfNeeded:] + 890
28  UIKit                               0x00000001064f2cea -[UINavigationController __viewWillLayoutSubviews] + 57
29  UIKit                               0x0000000106698c85 -[UILayoutContainerView layoutSubviews] + 248
30  UIKit                               0x00000001063cde40 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 710
31  QuartzCore                          0x0000000109e7b59a -[CALayer layoutSublayers] + 146
32  QuartzCore                          0x0000000109e6fe70 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
33  QuartzCore                          0x0000000109e6fcee _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
34  QuartzCore                          0x0000000109e64475 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 277
35  QuartzCore                          0x0000000109e91c0a _ZN2CA11Transaction6commitEv + 486
36  UIKit                               0x0000000106344216 _afterCACommitHandler + 174
37  CoreFoundation                      0x0000000105e98947 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
38  CoreFoundation                      0x0000000105e988b7 __CFRunLoopDoObservers + 391
39  CoreFoundation                      0x0000000105e8e50b __CFRunLoopRun + 1147
40  CoreFoundation                      0x0000000105e8de08 CFRunLoopRunSpecific + 488
41  GraphicsServices                    0x0000000109708ad2 GSEventRunModal + 161
42  UIKit                               0x000000010631930d UIApplicationMain + 171
43  SilverStoryClient                   0x00000001054b325f main + 111
44  libdyld.dylib                       0x000000010869092d start + 1
45  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

A: The stack trace shows that you're accessing the index 0 of an empty array.
You should check if your array is properly populated.
Or use guard keyword (or other if-else conditions) to avoid the index out of bounds issue.
Swift language references: guard statement.

A: There was this problem and I found the exact solution:
the problem is with the cell identifier name inside the storyboard attribute inspector and that of the "let cellIdentifier = "cell" ", if these names are different they will surely cause the sigabrt error.
so if anyone is have similar problem rectify that with this solution.
2015-12-01 11:31:26.301 The Place[2621:83370] * Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3512.29.5/UITableView.m:6547
2015-12-01 11:31:26.838 The Place[2621:83370] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason:

'unable to dequeue a cell with identifier Cell

must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
First throw call stack:
(
    0   CoreFoundation                      0x000000010f74cf45 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000111470deb objc_exception_throw + 48
    2   CoreFoundation                      0x000000010f74cdaa +[NSException raise:format:arguments:] + 106
    3   Foundation                          0x000000010fb955ee -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 198
    4   UIKit                               0x00000001100ac615 -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:] + 275
    5   The Place                           0x000000010f56deb4 _TFC9The_Place14ViewController9tableViewfS0_FTCSo11UITableView21cellForRowAtIndexPathCSo11NSIndexPath_CSo15UITableViewCell + 164
    6   The Place                           0x000000010f56e07f _TToFC9The_Place14ViewController9tableViewfS0_FTCSo11UITableView21cellForRowAtIndexPathCSo11NSIndexPath_CSo15UITableViewCell + 79
    7   UIKit                               0x00000001100bee2a -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 782
    8   UIKit                               0x00000001100bef3f -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 74
    9   UIKit                               0x0000000110094307 -[UITableView _updateVisibleCellsNow:isRecursive:] + 3187
    10  UIKit                               0x00000001100c7d1c -[UITableView _performWithCachedTraitCollection:] + 92
    11  UIKit                               0x00000001100af884 -[UITableView layoutSubviews] + 223
    12  UIKit                               0x000000011001de40 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 710
    13  QuartzCore                          0x00000001144b359a -[CALayer layoutSublayers] + 146
    14  QuartzCore                          0x00000001144a7e70 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
    15  QuartzCore                          0x00000001144a7cee _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    16  QuartzCore                          0x000000011449c475 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 277
    17  QuartzCore                          0x00000001144c9c0a _ZN2CA11Transaction6commitEv + 486
    18  QuartzCore                          0x00000001144ca37c _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92
    19  CoreFoundation                      0x000000010f678947 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    20  CoreFoundation                      0x000000010f6788b7 __CFRunLoopDoObservers + 391
    21  CoreFoundation                      0x000000010f66de2c CFRunLoopRunSpecific + 524
    22  UIKit                               0x000000010ff644f5 -[UIApplication _run] + 402
    23  UIKit                               0x000000010ff6930d UIApplicationMain + 171
    24  The Place                           0x000000010f56f1fd main + 109
    25  libdyld.dylib                       0x0000000111f7892d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)


text:
Q: Angular4 Routing Method I have the following routing in an angular project:
const sampleRoutes: Routes = [
  {
    path: ':fruit/show',
  },
  {
    path: ':fruit/edit'
  },
  {
    path: ':fruit/update'
  }
];

and I want to change it into a format like this:
const sampleRoutes: Routes = [
  {
    path: ':fruit/',
    children: [
      {
        path: 'show'
      },
      {
        path: 'edit'
      },
      {
        path: 'update'
      }
    ]
  }
];

However, Angular cannot catch the above routing. Does anyone know how to configure like this? Appreciate for any help.

A: For your information,
the correct routing should be like this:
const sampleRoutes: Routes = [
  {
    path: ':fruit',
    children: [
      {
        path: 'show'
      },
      {
        path: 'edit'
      },
      {
        path: 'update'
      }
    ]
  }
];

Remove the / after :fruit will get the correct routing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeScript compilation error on windows OS I have created a command in package.json using tsc-watch which is shown below:
npx tsc-watch --noClear --compiler ./node_modules/.bin/tsc --onSuccess 'node ./dist/src/index.js'

This works perfectly fine on mac but when I run it inside windows it throw below error:
\node_modules\.bin\tsc:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^

SyntaxError: missing ) after argument list

Not sure if there is anything wrong with compiler path or anything I am missing.
Thanks in advance.

A: I found a workaround by not specifying the compiler path and used below command to run it on windows:
"npx tsc-watch --noClear --onSuccess \"node ./dist/src/index.js\""


text:
Q: Configuring WWW prefix and HTTPS using Nginx I want Nginx to redirect all connections to: https://domain.xyz (remove www prefix if needed and always force https), so that for example:
http://wwww.domain.xyz/param and domain.xyz/param should redirect me to https://domain.xyz. To do that i made the following config in default server:
server {
        return 301 https://$host$request_uri;

        listen 80 default_server;
        listen [::]:80 default_server;
}

and "sub servers":
server {
        root /var/www/html;
        index index.html index.htm index.nginx-debian.html;
        server_name domain.xyz;
        location / {
                try_files $uri $uri/ =404;
        }

    listen [::]:443 ssl; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/domain.xyz/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/domain.xyz/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

server {

        server_name subdomain.domain.xyz;

        location / {
           proxy_pass http://localhost:8080;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_set_header X-Forwarded-Proto $scheme;
           proxy_set_header X-Forwarded-Port $server_port;
      }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/domain.xyz/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/domain.xyz/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

So i assumed the default server will do both for me (remove www prefix and force https), however when i try to open www.domain.xyz I'm getting this error in Chrome console:
Redirecting navigation www.domain.xyz -> domain.xyz because the server presented a certificate valid for domain.xyz but not for www.domain.xyz. To disable such redirects launch Chrome with the following flag: --disable-features=SSLCommonNameMismatchHandling

Except that everything works as expected. Also, as you can see i used letsencrypt to generate certs (for domain.xyz and subdomain.domain.xyz -- without wwww prefix (!) -- maybe that is the reason). So to sum it up:

*

*Is my config correct for the things i want to achieve?

*Should i be worried about that Chrome message?


text:
Q: KeyCloak 15.0.2 & Spring boot : after getting "Forbidden" Error access, the API persist sending the same error 403 even for authorized user I have a spring boot app, which delegate authentication and access management to KeyCLoak
: the linking parameters are defined in the application.proerties as follows:
## keycloak configuration:
keycloak.realm                      = Demo-Realm
keycloak.auth-server-url            = http://localhost:8080/auth
keycloak.ssl-required               = external
keycloak.resource                   = springboot-microservice
keycloak.credentials.secret         = xxxx-xxxx-xxxx-xxx-xxxxxxxxxxx
keycloak.use-resource-role-mappings = true
keycloak.bearer-only                = true

## Port
server.port=9090

When I started the app and try to access an API for using the access token for an authorized user provided by KeyCloak, a get the expected response with 200 code;
but when restart the app and  ommit the Authorization header, the API send 403 error and keeps sending the same error even after providing a valid access token again! So I have the restart the app the get it works again.
Here is my Configuration Class :
@Configuration
@KeycloakConfiguration
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class ResourceServiceConfig extends KeycloakWebSecurityConfigurerAdapter {

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper( new SimpleAuthorityMapper() );
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().permitAll();
        http.csrf().disable();
    }
}

My Controller:
@RestController
@RequestMapping("/workout")
public class WorkoutController {
    @Autowired
    private WorkoutService workoutService;

    @PostMapping("/add")
    public void addNewRecord(@RequestBody Workout newWorkout){
        workoutService.saveWorkout(newWorkout);
    }

    @RolesAllowed("admin")
    @GetMapping("/find/all")
    public List<Workout> findAllUserRecords(){
        return workoutService.findWorkouts();
    }

    @DeleteMapping("/{id}")
    public void deleteRecordById(@PathVariable Long id){
        workoutService.deleteWorkout(id);
    }
}

I'm new to KeyCloak. could anyone help.


text:
Q: Can't change local TFS 2010 paths Running VS 2010, I want to now build on TFS 2010. In Team Explorer, I change my connection from our old TFS 2008 build server to our new TFS 2010 server. Now I want to map my source control from the old local directory (C:\TFS) to new directory (C:\TFS2010). Using File -> Source Control -> Workspace, I can change the top level mapping of our projects to the new location, clicking the "recursive" check box.
However, I notice that while the top level mapping changes,  the local paths for the second tier folders don't change.
I tried removing all mapping, and I tried refreshing. Tried restarting VS2010. Tried renaming the old directory – that wasn't allowed.
I haven't tried getting latest from the top level, as that would take way too long and I probably don't have that much disk space.
Oddly, If I go to File -> Source Control -> Cloak while selecting a second tier project folder, it seems to think the mapping has already been updated for that tier.
Any ideas how I can re-map all my projects (or even just some of them), to a different local path?

A: Cloak and then uncloak the affected folders worked for me.

A: or File -> Source Control -> Workspaces -> Choose the workspace in question and you can remove and create it again

A: File -> Source Control -> Workspaces -> Choose the workspace in question and click "Edit".

A: The only answer I've been able to find so far is to edit your workspace definition and add a specific mapping for your TFS project. However, don't add a mapping that would be normally handled by the root level mapping cause if you do your setting will be ignored. If you add a unique mapping for your project it does seem to work. Not a perfect answer.
Since you can right click and remap the root I think the functionality was overlooked that would aloow you to right click and reset a project folder's specific mapping.
Looking forward to a better answer.

A: If you want to change the local path for the working directory of the Team Foundation Server (TFS), you need to go to File -> Source Control -> Advanced -> Workspaces, then select your workspace and click Edit.

In the next dialog change the mapping for the root TFS node to the new location on your hard drive.

A: remove the mapping from the root folder, once this is done you will be able to change the path.
Since the Root folder is mapped it is locking the entire structure to the same path.

A: TFS mapping can also be changed through Source Control Explorer. This is in Visual Studio 2017.

*

*Open Source Control Explorer under Team Explorer

*Right Click your TFS folder->Advanced->Remove Mapping (You can
change mapping without removing here in VS 2017)

*Change your Local Folder and click Change

From here, it will create the new folder if it doesn't already exist and map/download from TFS.


text:
Q: jQuery click/change even on select is not working I'm trying to capture the change of the drop list, however the click and change event didn't work no matter in ff or chrome. Here's the source html code:
<select class="select" id="querycond_select_Baitgenesymbol" style="max-width: 400px">
    <option>APC</option>
    <option>CTNNB1</option>
    <option>DNMT1</option>
    <option>ELF3</option>
    <option>EPHB2</option>
    <option>MRE11</option>

and jQuery:
$('.select').click(function() {
    alert("!!!!!!!")
});

I also tried to replace the click with change, but it didn't work out for me too.

A: Make sure to:

*

*include jQuery on your page

*Wrap your code in ready handler

*use change instead of click

$(function(){
  $('#querycond_select_Baitgenesymbol').change(function() {
    alert("!!!!!!!");
  });
});

A: works just fine ... http://jsfiddle.net/tXy6Q/  try adding it in document.ready()

*

*if the select box is added dynamically based on logic would recommend using live()
method..

*use the change event rather than click

*also check for any errors using firefox error console ..

A: Try this:
$(function(){
    $("#querycond_select_Baitgenesymbol").change(function(e){
        alert("here");
    });
});


text:
Q: understanding error message from forecast.gts I'm struggling with creating a forecast using the forecast.gts function. I'm getting an error message/warning that I do not understand and do need some guidance in where to look so I can find out how to setup the right forecast. The code that i'm running is:
SFA4 <- ts(SFA4, frequency=12, start=c(2012,1), end=c(2017,9))
library(forecast)
library(hts)

# Creating the gts model to be used for forecast
SFA5 <- gts(SFA4, characters=c(2, c(1, 2)))
f <- forecast.gts(SFA5, h=2, method="comb", fmethod="ets", algorithms = "lu", weights = "wls", lambda=0)

The error message that i'm getting is:
Warning message:
In value[[3L]](cond) :
  An error in LU decomposition occurred, the message was the following:
cs_lu(A) failed: near-singular A (or out of memory)
 Trying QR decomposition instead...

The data can be described in this way: I do have two customers bying the same products and have tried to excluded negative sales (replaced with zero) and month with no sales (adding 1 to all month where sales = zero).
I'm relatively new to R and forecasting and not trying to get my work done, but simply trying to find out where to look to find out which parameters to use for the algorithms, weights, method etc. The easiest way is naturally to run through all combinations and choose the forecast with the lowest variance. I do not get a warning when using method="bu", but I would like to understand how to find out which parameters to set when.
Here is the data (SFA4):
https://www.dropbox.com/s/2shh5pjojq4qzfu/Data1850.xlsx?dl=0

A: When using LU decomposition, it encounters the singularity problem, and hence it failed. You could try algorithms = "cg" that uses the conjugate gradient to reconcile the base forecasts. What matters most for the algorithms choice is the speed performance. Generally lu > cg > chol > recursive > slm (from faster to slower). They should return the identical results given the method (method) and forecasting method (fmethod).
?forecast.gts pops out the documentation for the forecast.gts function. It lists all the parameters and references that you would find helpful.


text:
Q: command 'go.tools.install' not found I am trying to install Go tools in my VS Code editor and when I select the View, CMD, Install and select Go: Install/Update tools, I get this -> "command 'go.tools.install' not found"
What am I doing wrong?

A: As seen in Microsoft/vscode-go issue 755:

For all guys who are stuck with command 'go.tools.install' not found problem on Windows.
Check if %GOPATH%\bin is in your PATH environment variable.
After half and an hour I finally figured out that PATH remains unchanged if you try to change it like set PATH=%PATH%.... You need explicitly change it in your system settings.

With recent Go installation, make sure GOROOT reference your Go installation folder.
I also like to set go.goroot to that folder in the settings of VSCode.
You don't need GOPATH: it defaults to %USERPROFILE%\go: make sure %USERPROFILE%\go\bin is in your PATH, before launching VSCode.

*

*unzip go1.13.6.windows-amd64.zip anywhere (not in %USERPROFILE%\go, since it is reserved for GOPATH)

*set GOROOT to C:\path\to\go (where you just uncompressed the Go archive)

*add %GOROOT%\bin to %PATH%

A: In my case I was on Ubuntu and installed go using snap so I did the following:

*

*Uninstall go from snap
sudo snap remove go

*Download go from the original source: https://go.dev/doc/install

*Install go as recommended in the source e.g.:
rm -rf /usr/local/go && tar -C /usr/local -xzf go1.19.1.linux-amd64.tar.gz

*Run the following to add the environment variables in the .bashrc:
echo export GOROOT=/usr/local/go >> ~/.bashrc
echo export GOPATH=\$HOME/go >> ~/.bashrc
echo export PATH=\$PATH:\$GOROOT/bin:\$GOPATH/bin >> ~/.bashrc

Note: Setting $GOROOT variable is obsolete in recent versions as discussed here

*Restart the VS Code to read the environment variables set above

*In VSCode press Ctrl+Shift+P and run again the GO: Install/Update tools, install everything selecting the checkboxes and you are good to GO!

A: In my case Go language was not installed so this command was not working from VS Code. Consider downloading and installing latest version of go language from https://go.dev/dl/
After I installed version 1.19.3 of go to my Windows 11 x64, the "go: install/Update Tools" command worked fine without any changes needed to be done to eviroment variables (PATH,GOROOT).(all changes were done by installer)
BTW restart of VSCODE really helps to make it work after installation of go.


text:
Q: Are macho headers backward compatible? Are the macho headers located in /usr/lib/mach-o backward compatible to executables over different iOS versions 4,5,6 etc? If so, where can I get the specific versions of them. I tried searching on the Apple Darwin site but they don't maintain them as a separate project.

A: The header files are compatible, but the Mach-O files as of iOS 6 are not compatible, having replaced the LC_UNIXTHREAD load command with an LC_MAIN (as well as adding a few other load commands which are unrecognized by otool and friends in previous versions of the OS). This also applies for Mountain Lion binaries, which for the same reason cannot be executed on Lion or earlier.


text:
Q: How to associate certain compiler flags with only certain targets I want to define some macros only for some make targets. eg.
all : process1 process2

prcoess1: process1.c process.h

prcoess2: process2.c process.h

%.o:%.c
        $(CC) $(CCOPTS) -o $@ $<

CCOPTS += -DEXTRA1
extra1 : clean all

CCOPTS += -DEXTRA2
extra2 : clean all

I want macro EXTRA1 to be defined only when I call make extra1. If I call make I don't want EXTRA1 to be defined. How do I accomplish this?

A: extra1 : CCOPTS += -DEXTRA1
extra1 : clean all

extra2 : CCOPTS += -DEXTRA2
extra2 : clean all

See §6.11 Target-specific Variable Values from the GNU make manual.


text:
Q: Translator, only accepts one word, why not the rest I am trying to create a program that translates English to PigLatin. I have most of the components, but if I enter in more than one word, it only translates the first word. Where is the issue and how do I fix it.
public class PigLatin{
public static String translate(String phrase){
String [] returnArray=phrase.split(" ");
String [] translateArray=new String [returnArray.length];
for(int i=0;i<returnArray.length;i++){
  translateArray[i]=translateWord(returnArray[i]);
}

return StringLib.join(translateArray, " ");//translated Array
 }
public static String translateWord(String word) {
String tword=word;
int indexVowel=indexOfFirstVowel(tword);
if(indexOfFirstVowel(tword)==0){
  tword=tword+"yay";
}
else {
  tword=tword.substring(indexOfFirstVowel(tword),tword.length())+tword.substring(0,indexOfFirstVowel(tword))+"ay";
}
return tword;
}
public static int indexOfFirstVowel(String word) {//check where the first vowel is
String vowels = "aeiouy";
String loweredWord=word.toLowerCase();
for (int index=0;index<loweredWord.length();index++){
    if(vowels.contains(String.valueOf(loweredWord.charAt(index)))){
        return index;
        }
}
return -1;
}

public static void main(String [] args){
Scanner inp=new Scanner(System.in);
System.out.println("Please enter a phrase:");
String trans=translate(inp.next());
System.out.println("Here is your phrase in Pig Latin.");
System.out.println(trans);

 }

String.join translates the array into a String and here is that code
public class StringLib {

public static String join(String[] strs, String sep) {
    String joined = "";

    if (strs.length > 0) {
        joined = strs[0];
        for (int i = 1; i < strs.length; i++) {
            joined = joined + sep + strs[i];
        }
    }

    return joined;
}

A: Change this line in your main method
 String trans = translate(inp.next());

Into
 String trans = translate(inp.nextLine());


text:
Q: Understanding the workflow of the messages in a generic server implementation in Erlang The following code is from "Programming Erlang, 2nd Edition". It is an example of how to implement a generic server in Erlang.
-module(server1).
-export([start/2, rpc/2]).

start(Name, Mod) ->
  register(Name, spawn(fun() -> loop(Name, Mod, Mod:init()) end)).

rpc(Name, Request) ->
  Name ! {self(), Request},
    receive
      {Name, Response} -> Response
    end.

loop(Name, Mod, State) ->
  receive
    {From, Request} ->
      {Response, State1} = Mod:handle(Request, State),
        From ! {Name, Response},
        loop(Name, Mod, State1)
  end.

-module(name_server).
-export([init/0, add/2, find/1, handle/2]).
-import(server1, [rpc/2]).

%% client routines
add(Name, Place) -> rpc(name_server, {add, Name, Place}).
find(Name)       -> rpc(name_server, {find, Name}).

%% callback routines
init() -> dict:new().
handle({add, Name, Place}, Dict) -> {ok, dict:store(Name, Place, Dict)};
handle({find, Name}, Dict)       -> {dict:find(Name, Dict), Dict}.

server1:start(name_server, name_server).
name_server:add(joe, "at home").
name_server:find(joe).

I tried so hard to understand the workflow of the messages. Would you please help me to understand the workflow of this server implementation during the executing of the functions: server1:start, name_server:add and name_server:find?

A: This example is an introduction to the behavior concept used in Erlang. It illustrates how you can build a server in 2 parts:
The first part is the module server1 which contains only generic features that could be used by any server. Its role is to maintain available some
information (the State variable) and to be ready do answer some request. This is what the gen_server behavior does, with much more features.
The second part is the module name_server. This one describe what a particular sever does. It implements interfaces for the user of the server and internal functions (callback)  which describe what to do for each specific user request.
Lets follow the 3 shell commands (see diagram at the end):
server1:start(name_server, name_server). the user calls the start routine of the generic server, giving 2 informations (with the save values), the name of the server he wants to start, and the name of the module which contains the callbacks. with this the generic start routine
1/ calls back the init routine of name_server to get the server state Mod:init(), you can see that the generic part does not know which kind of information it will keep; the state is created by the name_server:init/0 routine, the first callback function. here it is an empty dictionary dict:new().
2/ spawns a new process calling the generic server loop, with the 3 informations (server name, callback module and initial server state) spawn(fun() -> loop(Name, Mod, Mod:init()). The loop itself just starts and wait for a message of the form {,} in the receive block.
3/ registers the new process with the name name_server register(Name, spawn(fun() -> loop(Name, Mod, Mod:init()) end)).
4/ returns to the shell.
At this point, in parallel to the shell, there is a new living process named name_server running and waiting for a request. Note that generally this step is not done by the user, but by the application. It is why there is no interface to do that in the callback module, and that the start function is directly called in the generic server.
name_server:add(joe, "at home"). The user adds an information in the server, calling the add function of the name_server . This interface is here to hide the mechanism to call the server, and it runs in the client process.
1/ The add function calls the rpc routine of the server with 2 parameters rpc(name_server, {add, Name, Place}): the callback module and the request itself {add, Name, Place}. the rpc routine is still executed in the client process,
2/ it builds a message for the server made of 2 information: the pid of the client process (here the shell) and the request itself then send it to the named server: Name ! {self(), Request},
3/ The client waits for a response. Remember that we left the server waiting for a message in the loop routine.
4/ The message sent matches the expected format {From, Request} of the server, so the server enters in the message processing. First it callback the name_server module with 2 parameters: the request and the current state Mod:handle(Request, State). the intent is to have a generic server code, so it is not aware of what to do with the requests. In the name_server:handle/2 function, the right operation is done. Thanks to pattern matching, the clause handle({add, Name, Place}, Dict) -> {ok, dict:store(Name, Place, Dict)}; is called and a new dictionary is created storing the key/value pair Name/Place (here joe/"at home"). the new dict is returned with the response in a tuple {ok,NewDict}.
5/ Now the generic server can build the answer and return it to the client From ! {Name, Response}, en re-enter in the loop with the new state loop(Name, Mod, State1) and wait for the next request.
6/ The client who was waiting on the receive block get the message {Name, Response} and can then extract the Response and return it to the shell, here it is simply ok.
name_server:find(joe). The user wants to get an information from the server. The process is exactly the same as before, and it is the interest of the generic server. whatever the request is, it does the same job. When you will look into gen_server behavior, you will see that there are several kind of accesses to the sever such as call, cast, info... So if we look at the flow of this request:
1/ call rpc with callback module and request rpc(name_server, {find, Name}).
2/ send a message to the server with client pid and request
3/ wait for the answer
4/ the server receive the message and callback the name_server with the request Mod:handle(Request, State), it get the response from the handle handle({find, Name}, Dict) -> {dict:find(Name, Dict), Dict}. which returns the result of the dictionary search and the dictionary itself.
5/ the server build the answer and sent it to the client From ! {Name, Response}, and re-enter in the loop with the same state, waiting for the next request.
6/ The client who was waiting on the receive block get the message {Name, Response} and can then extract the Response and return it to the shell, now it is the place where joe is: "at home".
the next picture shows the different message exchanges:


text:
Q: AWS ELB Nginx Remote Address I am using nginx behind AWS ELB. When i get response from server Remote Address is of ELB not of server is it possible to have server IP instead of AWS ELB.

A: When the AWS ELB sends requests to an nginx server, it adds a header to the request called "X-Forwarded-For", with the value being the "the IP address of a client when you use an HTTP or HTTPS load balancer"
So your nginx server configuration should contain a line such as:
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

To allow the application that nginx serves to see that header.

A: No you can't, if you would that would contradict the whole point of the ELB, and expose you EC2 instance to outside traffic. In that case the ELB won't be able to balance the load on your instance and cause it to crash.
If you want to access your instance IP directly, don't use an ELB.

A: You can make change in log format of Nginx and add X-forward, this will print both elb and original WAN ip of the request


text:
Q: How to convert NUM to INT in R? I am trying to convert numeric format to an integer in R. This is essential to a part of the project where I am using java code to run some simulations (which reads this particular data as int).
I tried both round(x$var, 0) and trunc(x$var). Both of them run successfully, but when I str(x), x$var is still num.  x is a dataframe.

A: Use as.integer:
set.seed(1)
x <- runif(5, 0, 100)
x
[1] 26.55087 37.21239 57.28534 90.82078 20.16819

as.integer(x)
[1] 26 37 57 90 20

Test for class:
xx <- as.integer(x)
str(xx)
 int [1:5] 26 37 57 90 20

A: You can use convert from hablar to change a column of the data frame quickly.
library(tidyverse)
library(hablar)

x <- tibble(var = c(1.34, 4.45, 6.98))

x %>%
  convert(int(var))

gives you:
# A tibble: 3 x 1
    var
  <int>
1     1
2     4
3     6


text:
Q: In Azure Blob Storage what is the difference between Virtual Directory and Containers? I want to build scalable storage but I am confused as to when you would use Virtual Directory as opposed to Containers. Which is more performant when uploading images using C# .NET Core, or if they both have their own use cases, what would they be?
I was expecting that a container would be used as below:

*

*PhoneImages (Container)

*

*iPhone11 (Virtual Directory) then inside that virtual directory

*

*iPhone11 Side Image

*iPhone11 Rear Image

However, it occurred to me that you could use a container for each phone model as below:

*

*iPhone14Images

*SamsungS21Images

*GooglePixel7Images

A: A virtual directory is essentially just a group of blobs with the same naming prefix. A container is more like a physical folder. You could potentially use them interchangeably but there are differences.
One key difference for your use case may be that a container name can only be 63 characters long and only contain certain characters. A blob name - including the prefix - can be up to 1024 characters and use any combination of characters. Another thing to note is that a container can be empty whereas a virtual directory can't be as it is a collection of blobs. If there are no blobs with the virtual directory prefix it effectively doesn't exist.
References:

*

*https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction

*https://learn.microsoft.com/en-us/rest/api/storageservices/Naming-and-Referencing-Containers--Blobs--and-Metadata


text:
Q: IDL set value to cell I am writing test app, that should read file name and print it in cell of spreadsheet. I can't understand how to put filename value to cell. Here is my code:
PRO test
;D:\Proj\2\test1\data\HTML5_Logo_256.png
title='my example'
base = WIDGET_BASE(xsize=500, ysize=400, MBAR=mbar, TITLE=title, COLUMN=3, TLB_FRAME_ATTR=1)
fmenu = WIDGET_BUTTON(mbar, VALUE='File')
open_file = WIDGET_BUTTON(fmenu, value='Open file', uvalue='Open')
table = WIDGET_TABLE(base, XSIZE=4, YSIZE=4, COLUMN_LABELS=["name", "FID", "size", "foo"], X_SCROLL_SIZE=0)

WIDGET_CONTROL, base, /REALIZE
info={base:base}
infoptr=PTR_NEW(info)
WIDGET_CONTROL, base, SET_UVALUE=infoptr
XMANAGER,'test', base,/NO_BLOCK
END

PRO test_EVENT, event

WIDGET_CONTROL,event.top, GET_UVALUE=infoptr
info=*infoptr
WIDGET_CONTROL,event.id, GET_UVALUE=widget

IF (widget EQ 'Open') THEN BEGIN
  filename=DIALOG_PICKFILE(PATH='D:\Proj\2')
  envi_open_file, filename, r_fid=fid

  if (fid eq -1) then return

ENVI_FILE_QUERY, fid, filename=filename, ns=ns

print,'filename=',filename
WIDGET_CONTROL, table, SET_VALUE = filename ; here is my attempt

ENDIF

END


text:
Q: Static analysis of actors in Scala I am searching for Papers and programs for the static analysis of actors in Scala. Is there any program which allows the static detection of message passing errors in Scala (using Akka Actors)?
I've only found the Paper "Detection of Asynchronous Message Passing Errors Using Static Analysis" by Christakis and Sagonas about the analysis of message passing errors in Erlang. They wrote another Paper called "Static Detection of Deadlocks in Erlang". I've not yet found any source code by them which they contributed to the dialyzer but I think the same methods should work with Scala too.


text:
Q: Python read two dictionaries compare values and create third dictionary I have two dictionary files that I want to compare.  I need to know if a value from one dictionary occurs in the other dictionary.  The keys are not the same so I can't go based on keys.
Goals:

*

*Does same value exist in both dictionaries?

*Print the values that do not occur in the other dictionary.

*Create a new dictionary with the Keys, values from both the dictionary that match and print dictionary to screen.

I'm able to search both dictionaries and find 69 different entries.
My issues are:

*

*I suspect there is a much simpler way of doing this and

*I suspect a better approach overall.

*I'm not creating the third dictionary with the values/keys from the two when matched.

Current Code:
#!/usr/bin/python

# Open Files and Build dictionaries.

ackg2shipping = open('AirCheckG2_ShippingLog.txt', 'r', encoding='ascii')
dAckg2 = {}
for line in ackg2shipping:
    if not line.strip():
        continue
    row = line.split(',')
    # creating unique key as one does not exist in file:
    mfgDate = row[2]
    serialNumber = row[5]
    dAckg2[mfgDate] = serialNumber

macAddressLog = open('MacAddress.dat', 'r', encoding='ascii')
dMacaddress = {}
for line in macAddressLog:
    if not line.strip():
        continue
    row = line.replace(", ", ",").split(',')
    macAddress = row[0]
    serialNum2 = row[1]
    if serialNum2.find("_2") != -1:
        continue
    if serialNum2.find("HM") != -1:
        continue
    if serialNum2.find("-") != -1:
        continue
    if serialNum2.find("Min") != -1:
        continue
    if serialNum2.find("Max") != -1:
        continue
    dMacaddress[macAddress] = serialNum2

for ackValue, macValue in zip(dAckg2.items(), dMacaddress.items()):
        if ackValue == macValue:
            print('Ok', ackValue, macValue)
        else:
            print('Not', ackValue, macValue)

match = 0
nomatch = 0

for ackKey, ackValue in dAckg2.items():
    for macKey, macValue in dMacaddress.items():
        if ackValue == macValue:
            # print("Debug: ", macValue, ackValue, "Match")
            match += 1
        else:
            # print("no match")
            # print("Debug: ", macValue, ackValue)
            nomatch += 1

print("Matched: ", match)
print("Not Matched:", nomatch)

match = 0
nomatch = 0
for macKey, macValue in dMacaddress.items():
    for ackKey, ackValue in dAckg2.items():
        if macValue == ackValue:
            # print("Debug: ", macValue, ackValue, "Match")
            match += 1
        else:
            # print("no match")
            # print("Debug: ", macValue, ackValue)
            nomatch += 1

print("Matched: ", match)
print("Not Matched:", nomatch)
missingSerials = (len(dAckg2) - match)
# noinspection PyPep8
print(missingSerials)

A: If you're only concerned about the values, the dict.values() method is probably what you want.
d1_values = set(d1.values())
d2_values = set(d2.values())
in_both = d1_values & d2_values
not_in_both = d1_values ^ d2_values

I'm not sure exactly what your third requirement entails.  Is it something like this?
new_dict = {}
for k, v in d1.items():
    if v in in_both:
       new_dict.update((k, v))
for k, v in d2.items():
    if v in in_both:
        new_dict.update((k, v))
print(new_dict)


text:
Q: Facebook Game White Screen, systematic across many games Some of my players who saw a White Screen while Facebook had our App turned off for an update we missed can not get the White Screen to go away now.  I've been searching and I find similar mentions of this White Screen on many other Facebook game support forums with no good answer.  Here is a comment from a customer I've put through the ringer trying to fix it.  I've seen identical comments on other games forums.  The main thing here to point out is that if he logs in with his wife's FB our game works fine, same computer/browser, everything.  This leads me to believe there is something Facebook is catching on their end.  The only thing I can think of now is for players effected by white screens is to delete and then reinstall the app.
"At this point the following has been done: Clear browser history. Cleared Flash cache. Enabled Secure browsing in FB. None of this solves the issue. But here's something interesting: I logged on with my friends account who had never played Slot Stories. The app loaded just fine. On my account however, nothing. And from past comments of other users, they did the same. I think you need to look into why If it will load from a new FB account on the SAME computer in the SAME browser, then the browser history, flash cache, and internet security settings have NOTHING to do with the problem!!"
If anyone has any insight on why our game would work from a different facebook account on the same computer please let me know.  Also, please let me know what to tell all my players to do, because we've tried everything!

A: My users are reporting that deleting and reinstalling the Facebook apps works to fix the white screen.  Also, all of their coins/levels were saved.


text:
Q: Why is $x$ not equal to $75$ degrees?
Someone told me,

Draw $B C$. Let $\angle D B C=y$. Then $30+2 y=180 \Rightarrow y=75$. Now, notice
that ABCD is a cyclic quadrilateral. As a result, $x+y=180 \Rightarrow x=105$ but

I cannot see their logic.

A: The following may be easier: Since $\text{m}\angle BDC = 30$, the arc $BC$ must span twice that, or $60$ degrees. Then, by symmetry, we have arc $CD$ spanning $\frac{360-60}{2} = 150$ degrees, so arc $BCD$ spans $210$ degrees. Therefore, $\text{m}\angle BAD = \frac{210}{2} = 105$ degrees.

A: Draw diameter from D , it meets the circle at E. we have:
$\overset{\frown}{EB}=\frac 12 [\overset{\frown}{EB}=60^o]=30^o$
$\Rightarrow \overset{\frown}{BCA}=30+180=210^o$
$\Rightarrow x=\frac 12\overset{\frown}{BCA}=\frac {210}2=105^o$

A: As triangle BCD is isosceles triangle and angle BDC = 30, we get angle DBC = DCB = 75.
Join AC.
BC is common chord so angle BDC = angle BAC = 30.
Similarly angle DAC = angle DBC = 75 as CD is the common chord.
You can see the theorem here Angles in same segment are equal.
Angle x = angle DAC + angle BAC = 105


text:
Q: When is the proper time to minify css and js with git workflow? New to web development, and have been utilizing a git repository for my wordpress website. I maybe over thinking this but here goes...
Currently, my workflow is as follows:

*

*Make changes locally and commit to dev branch

*Create release tags for appropriate site versions

*Deploy tag on staging, then to production.

When working on my local machine, URLs to images are on the local box. When I am happy with a release, I upload these images (compressed, resized) to an an S3 bucket, but this also involves going back and updating their src in any code.
There are lots of .css files, for my theme, and all the installed plugins. I was thinking about using Grunt/Gulp to minify all of this, along with concatenation. Then, store these files to an S3 bucket, similar to the images.
After minification, wouldn't I have to update all the references in the plugin/other PHP files to include the "min" version of it?
What are the benefits (if any), of minifying before deployment vs. using a plugin to do it, after deployment?

A: Probably the simplest solution is to have the WordPress environment tell your plugin what files to load. On your development install of WP, you should set the constants WP_DEBUG and SCRIPT_DEBUG to true. Then in your functions.php or main file of the plugin, you can do something like this for the image path:
if ( defined( 'WP_DEBUG' ) && true === WP_DEBUG ) {
    define( 'IMG_PATH', '/path/to/dev/images' );
} else {
    define( 'IMG_PATH', '/path/to/S3/bucket' );
}

That will allow you to set your image paths once and have the code load the correct one depending on the environment:
<img src="<?php echo IMG_PATH;?>/header.jpg" />

You can do something similar to this when enqueuing js/css:
//define the base path to our assets
$basepath = plugin_dir_url( __FILE__ );

//setup the production names for the files
$js_file = 'scripts.min.js';
$css_file = 'styles-compressed.css';

//check for WP_DEBUG constant status
if( defined( 'WP_DEBUG' ) && WP_DEBUG ) {

    //check for SCRIPT_DEBUG constant status
    if( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
        $js_file = 'scripts.js';
        $css_file = 'styles-development.css';
    }
}

//load the files
wp_enqueue_script( 'plugin_scripts', $basepath . '/js/' . $js_file  );
wp_enqueue_style( 'plugin_styles', $basepath . '/css/' . $css_file  );

Here is some documentation on debugging in WordPress
Hope this helps!


text:
Q: Static IP for Parse Server on Heroku I have some Parse Server installations running on Heroku, and I need to get them static IP addresses.  I've looked into the various add-ons such as Fixie and QuotaGuard Static.  Their documentation indicates that the connection code needs to be changed to use the proxy to get a static IP.  I would really like to avoid editing the Parse Server code, because that will make it much harder to update when a new release of Parse Server comes out.  Is there any way to get a static IP that's transparent to the code running in the dyno?
Should this be on serverfault?

A: There's no way to get a static IP without using a proxy (and changing code).
From Heroku:

"The IPs in use by Heroku at any given time are highly dynamic."

See:
https://help.heroku.com/JS13Y78I/i-need-to-whitelist-heroku-dynos-what-are-ip-address-ranges-in-use-at-heroku


text:
Q: Is Spring affected by the underlying database? I am trying to write a guide on how to get started with Spring-boot+Tomcat+React.js
This is an educational piece for a project with a lot of different developers. We know that we will use PostGreSQL, but I want the guide to be to the point as much as possible.
Is the Spring code at all affected by the underlying database choice?
From: https://spring.io/blog/2015/09/01/react-js-and-spring-data-rest-part-1-basic-features

Spring Boot makes it extremely convenient for programmers to quickly develop Spring applications using an in-memory database, such as H2, HSQLDB, and Derby. These databases are lightweight, easy to use, and emulates other RDBMS with the help of JPA and Hibernate. Obviously, they don't provide persistent storage; but they a fast way to test persistent functions of your Spring Boot application without going through the hassles of installing a database server. They are great to use during development when you need to populate your database once your application starts, test your persistent entity mappings, and remove any data when your application ends. To use the embedded databases, you don't need any special configuration, not even any connection URL. If you are using Maven, you only specify the dependency of the database to use in the POM file. Spring Boot automatically sets up the in-memory database for your use when it finds the database on your classpath.
In-memory databases are useful in the early development stages in local environments, but they have lot's of restrictions. As the development progresses, you would most probably require an RDBMS to develop and test your application before deploying it to use a production database server, such as Oracle, MySQL, or PostgreSQL.

Would for instance the class (also from: https://spring.io/blog/2015/09/01/react-js-and-spring-data-rest-part-1-basic-features)
@Data
@Entity
public class Employee {
    private @Id @GeneratedValue Long id;
    private String firstName;
    private String lastName;
    private String description;

    private Employee() {}

    public Employee(String firstName, String lastName, String description) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.description = description;
    }
}

have to be modified in anyway when using PostGreSQL as opposed to an in-memory database?
Cheers and kind regards,
Filip

A: No.
You configure a database in the hibernate configuration. For plain Hibernate it is hibernate.properties or hibernate.cfg.xml. It doesn't affect persistent classes.


text:
Q: Docker-compose could not translate host name "postgres" I'm fairly new to Docker.
When I run docker-compose up, I would get the following error.
PG::ConnectionBad
could not translate host name "postgres" to address: Name does not resolve

In the log, it says the following
postgres_1   | The database cluster will be initialized with locale "C".
postgres_1   | The default database encoding has accordingly been set to "SQL_ASCII".
postgres_1   | The default text search configuration will be set to "english".
postgres_1   |
postgres_1   | Data page checksums are disabled.
postgres_1   |
postgres_1   | initdb: directory "/var/lib/postgresql/data" exists but is not empty
postgres_1   | If you want to create a new database system, either remove or empty
postgres_1   | the directory "/var/lib/postgresql/data" or run initdb
postgres_1   | with an argument other than "/var/lib/postgresql/data".

This is my docker-compose setup.
# docker-compose.yml

version: '3'
services:
  postgres:
    image: postgres:9.6-alpine
    volumes:
      - postgresql-data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
  app:
    build:
      context: .
    command: "bundle exec rails server -b 0.0.0.0"
    ports:
      - "3020:3000"
    depends_on:
      - postgres
volumes:
  postgresql-data:

# Dockerfile

FROM ruby:2.3.7-alpine

ENV LANG C.UTF-8
ENV RAILS_ENV=development

RUN apk add --update --no-cache --virtual=builders \
      alpine-sdk build-base linux-headers ruby-dev zlib-dev postgresql-dev
RUN apk add --update --no-cache \
      libc6-compat libc-dev zlib ruby-json tzdata yaml less curl postgresql
RUN mkdir /app

WORKDIR /app

COPY Gemfile /app/Gemfile
COPY Gemfile.lock /app/Gemfile.lock
RUN bundle install
COPY . /app

# database.yml
default: &default
  adapter: postgresql
  encoding: utf8
  host: postgres
  username: postgres
  password:
  port: 5432

development:
  <<: *default
  template: template0
  database: todo_development

What am I doing wrong here??
If I change host from postgres to localhost in my database.yml, I get the following error.
Connection refused Is the server running on host "localhost" (127.0.0.1)


text:
Q: How to unzip files after an install using Advanced Installer I have a huge zipped folder with wav files in it (o.5 GB zipped), that needs to be unzipped after installation.  I'm using Advanced Installer.  I was hoping there would be some custom action that would unzip the files for me after the install is complete, but no such luck.  A quick search for using command line to unzip files, also didn't yield much results, other than powershell scripts.
What's the best way to unzip files after an install using Advanced Installer (deploying on a Windows7/10 machine)?

A: I ended up just unzipping the files and adding them in unzipped form to the Advanced Installer.  Their built in compression is pretty good.  The only issue is that the MSI build takes 7 minutes now, but I can live with that.


text:
Q: Leaflet Awesome-Markers (Adding Numbers) I am using the Leaflet.Awesome-Markers plugin with LeafletJS.
I have implemented it correctly, however now I'd like to be able to use numbers from 0 - 9 to represent markers.
Here's a JS Fiddle implementation to show how the plugin behaves.
http://jsfiddle.net/fulvio/VPzu4/200/
The plugin allows the use of font-awesome icons and glyph icons (both of course, do not offer any 0 - 9 numbers as icons. argh!)

*

*http://getbootstrap.com/components/#glyphicons

*http://fortawesome.github.io/Font-Awesome/cheatsheet/
The documentation mentions the ability to use extraClasses and I was wondering whether anyone could point me in the right direction as to how to leverage from this in order to display numbers rather than icons or whether there is simply another way to achieve this.
Thanks in advance for your help.
UPDATE:
Thanks for the comment @Can.
The author of awesome-markers got another tree where he added exactly what you are looking for awesome-markers with numbers/letters be sure to grab the unminified JS.

A: Another strategy is to use the Leaflet.ExtraMarkers plugin
Code the numeric marker with these options:
var numMarker = L.ExtraMarkers.icon({
icon: 'fa-number',
number: 12,
markerColor: 'blue'
});
L.marker([41.77, -72.69], {icon: numMarker}).addTo(map);

A: I have tried Numbered Markers plugin, but it icon is not pretty as other Awesome Markers, and make page layout style inconsistent, so I made small changes in Awesome-Markers plugin to make it support numbers. It is very simple.

*

*this is Numbered Markers plugin effect, if you like it please skip my answer.

*change leaflet.awesome-markers.js line 2, add html:""
L.AwesomeMarkers.Icon = L.Icon.extend({
options: {
    iconSize: [35, 45],
    iconAnchor:   [17, 42],
    popupAnchor: [1, -32],
    shadowAnchor: [10, 12],
    shadowSize: [36, 16],
    className: 'awesome-marker',
    prefix: 'glyphicon',
    spinClass: 'fa-spin',
    extraClasses: '',
    icon: 'home',
    markerColor: 'blue',
    iconColor: 'white',
    html : ""
},

*change leaflet.awesome-markers.js line 80,
return "<i " + iconColorStyle + "class='" + options.extraClasses + " "
+ options.prefix + " " + iconClass + " " + iconSpinClass + " "
+ iconColorClass + "'>" + options.html + "</i>";

*when creating icon, call like before
var jobMarkerIcon = L.AwesomeMarkers.icon({
icon: '',
markerColor: 'darkblue',
prefix: 'fa',
html: (i+1)
});

*comment out line 45 and 47.

*the result is like below screenshot.

*code changes diff shows below.

A: Instead of using the Awesome-Markers plugin, you could follow this article on creating numbered markers in Leaflet:
http://blog.charliecroom.com/index.php/web/numbered-markers-in-leaflet
The associated Gist is here:
https://gist.github.com/comp615/2288108
An simple example of how this would work is as follows:
// The text could also be letters instead of numbers if that's more appropriate
var marker = new L.Marker(new L.LatLng(0, 0), {
    icon:   new L.NumberedDivIcon({number: '1'})
});

A: If you don't want to use the font-awesome, a fairly simple solution presented here:
Simple Numbered Markers
it doesn't need any extra library. It's already in leaflet. Just create a CSS class with icon image like this:
.number-icon
{
    background-image: url("images/number-marker-icon.png");
    background-size: 40px 40px;
    background-repeat: no-repeat;
    margin: 0 auto;
    text-align:center;
    color:white;
    font-weight: bold;
}

Then create icon like this:
var numberIcon = L.divIcon({
      className: "number-icon",
      shadowSize: [20, 30], // size of the shadow
      iconAnchor: [20, 40],
      shadowAnchor: [4, 30],  // the same for the shadow
      popupAnchor: [0, -30],
      html: variable_containing_the_number
});

var marker = new L.marker([lat, long],
{
    icon: numberIcon
});


text:
Q: Want to compare string with null iOS sdk I want to comapre my string with null values I am getting from my local database.
I tried if (exe_lbl_data.text==nil) and also if (exe_lbl_data.text=@"(null)") but both are showing false.

A: try below statement :
[string length] == 0

or
[string isKindOfClass:[NSNull class]];

A: try one or both of the following:
if (nil == str || NSNull.null == (id)str) {
  …
}

In this case, you need to define what Null is. There is a Null type (NS/CF-Null), and there is the concept of the Null pointer. It varies by case (that is, what is returned to you?).


text:
Q: Git checkout fails with because local changes ... without local changes? Using Git 2.7.4 I made some changes to a branch. Commit and  push to the branch.
[user:~/terraform] mybranch ± git status
On branch DIC-98-rhel-lb0
nothing to commit, working directory clean
[user:~/terraform] mybranch ±

[user:~/terraform] mybranch ± git push origin mybranch
Everything up-to-date

When I try to switch to master
[user:~/terraform] mybranch ± git checkout master
error: Your local changes to the following files would be overwritten by checkout:
    azure-openshift/.gitignore
    azure-openshift/bastion.tf
    azure-openshift/bootstrap.sh
    azure-openshift/bootstrap.tfvars
    azure-openshift/cns.tf
    azure-openshift/infra.tf
    azure-openshift/master.tf
    azure-openshift/openshift.auto.tfvars
    azure-openshift/openshift.variables.tf
    azure-openshift/revproxy.tf
Please, commit your changes or stash them before you can switch branches.
Aborting
[user:~/terraform] mybranch 1 ±

I can also do git reset first, with the same result.
What am I missing?

A: Most likely those files are ignored in your current branch (mybranch), but they are part of the master branch (perhaps they were accidentally committed at some point?). So while your current branch is clean, checking out master would overwrite those files and risk losing that data.
If you know that it's safe to overwrite those files, then you can tell git that you're quite sure you want to check out master with the -f flag:
git checkout -f master

If you're not sure, then you can try rebasing or merging master into your issue branch and working through any conflicts, etc.

For example, let's say you accidentally included a file named foo.temp, which is a log file generated when you run builds, in your master branch.
You then create a new branch, remove_foo, and add foo.temp to your .gitignore. You build (thus modifying foo.temp), commit and push your changes to the server.
Everything looks good. git status returns clean.
You then attempt to checkout master and get an error: foo.temp will be overwritten with the version in master. Git is trying to protect your work.
Fortunately, you know that this is a temporary issue, so you use git checkout -f master because you know that it's okay if foo.temp is overwritten.
Eventually, remove_foo will be peer-reviewed and merged into master and this little annoyance will go away.

If you attempted to remove some files which were accidentally included in the repo, then you may find this helpful:
Remove a file from a Git repository without deleting it from the local filesystem


text:
Q: OpenCV - How to defined a variable of type CvvImage in Opencv 2.3? I'm writing a program to capture image frames from a camera and to dispay them on the MFC  picture control window. My program is using MFC in OpenCV 2.3 and Visual studio 2010.
but I am not able to use the function CvvImage.
It says it is undefined.  This function comes under the highgui.h header file.  When I check the header file and compared it with Opencv 1.0 I saw that this function is not defined here.
When I use this program on opencv 1.0 and visual studio 2008 it works fine.  and executes.
but using visual studio 2010 and opencv 2.3 it is not defined.
please help use the CvvImage or tell me the equivalent used in opencv 2.3.
I do no want to use IplImage. because then I am not able to place my image frame on the MFC picture control window.
Thank you

A: WEll after many days thinking i finally got the answer.
What we need to do it to add a class CvvImage.cpp and the header file CvvImage.h to the open cv directory.
and in the main program we need to define #include "CvvImage.h"


text:
Q: jquery $.ajax to php problem i have two problems with jquery $.ajax.
first problem is ihave a php file named action.php and here the code:
if($_GET['action']=='add'){
    //rest of the code here
}

And i use jquery $.Ajax function to call that when form fills:
$.ajax({type:"POST", url:"action.php?action=add", data:$("#form").serialize(), cache:false, timeout:10000});

this works but i wanted to know is there anyway to send the action=add code with data and not the url?
and the second problem that i have is that i have a link:
delete row from mysql where id is 4

and a jquery function:
    function deleteUser(id){
    $.ajax({type:"POST", url:"action.php?action=delete", data:"id="+id, cache:false, timeout:10000});}

and of course the action.php code:
if($_GET['action']=='deletestudent'){
    mysql_query("DELETE FROM `students` WHERE `student_id` = {$_POST['id']}");
}

but it doesn't work.what should i do?

A: First part: Yes
var postData = $("#form").serialize();
postData.action = 'add';
$.ajax({
    type:"POST"
  , url: "action.php"
  , data: postData
  , cache: false
  , timeout:10000
});

For the 2nd part: that isn't working because your "action" values are not congruent: delete vs deletestudent.  Nor are your function names: delete() vs deleteUser()
Also, I'd recommend applying some SQL injection protection in that query as well.

A: You have a function deleteUser() and you are using delete() even you're sending post action is delete while you're php script is looking for deletestudent
make your onclick onclick="deleteUser(4);"
and change your action from
$.ajax({url:"action.php?action=delete&id="+id, cache:false, timeout:10000});}

to
$.ajax({url:"action.php?action=deletestudent&id="+id, cache:false, timeout:10000});}

A: For the first problem:
You can add to your form a hidden input with the name/value you need. Example:
<input type="hidden" name="action" value="add" />

For the second problem:
According to your code, it seems that you are send "delete" but in the condition you are testing if equal to "deletestudent", maybe that's your problem.

A: chnage the type to GET o remove it, $.ajax default type is GET
$.ajax({url:"action.php?action=delete&id="+id, cache:false, timeout:10000});}

in php change your
....WHERE `student_id` = {$_GET['id']}");


text:
Q: WordPress Mailerlite - How to include mailerlite SDK in plugin I'm trying to create a plugin such that whenever the user registers he automatically gets added to mailerlite group
but I'm getting an error after including the mailerlite sdk such that the class doesn't exist. You can find my code and the error here
https://github.com/asamolion/mailerlite-auto-signup
I just can't seem to find out how to include the API in the plugin.
Any help will be appreciated.

A: This is really PHP issue, not specifically WP - the class is namespaced, so you need:
$mailerlite = new MailerLiteApi\MailerLite;


text:
Q: .htaccess redirect excluding sub-domains I have the following in my .htaccess to redirect all old domain names which point to the same location to the new domain, but this doesn't allow any sub domains of the new domain name to work - any idea how to amend the code to allow sub-domains would be appreciated:
RewriteCond %{HTTP_HOST} !^www\.newdomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]

A: Redirect subdomain to subdomain under a new domain...
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$ [NC]
RewriteRule ^(.*)$ http://%1.newdomain.com/$1 [R=301,L]

A: Thanks Brian - it certainly helped - the final outcome is the following:
RewriteCond %{HTTP_HOST} !^www\.newdomain\.com$ [NC] [AND]
RewriteCond %{HTTP_HOST} !^(.*)\.newdomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]

Thanks for your time.


text:
Q: Ant script: Prevent duplication of JAR in javac-classpath war-lib I have a ANT script and I have a lot of duplicated path to same set JAR files.
But there is so many double wording in the classpath and also in the war element.
<path id="my.classpath">
  <pathelement location="folderA/subFolderA/1.0/A.jar"/>
  <pathelement location="folderC/subFolderB/1.0/B.jar"/>
  <pathelement location="folderF/subFolderZ/2.0/Z.jar"/>
  <pathelement location="compile/subFolderX/1.0/onlyForJavac.jar"/>
</path>
....
<javac ...>
 <classpath refid="my.classpath" />
</javac>
....
<war ...>
 <lib file="folderA/subFolderA/1.0/A.jar"/>
 <lib file="folderC/subFolderB/1.0/B.jar"/>
 <lib file="folderF/subFolderZ/2.0/Z.jar"/>
 <lib file="moreFolderF/subFolderZ/2.0/additionFile.jar"/>
 <lib file="moreFolderF/subFolderZ/2.0/additionRuntimeFile.jar"/>
</war>

I want to summary them into ONE list which is easier to keep update.
But I am blocked as I have no idea how to share a path-like-structure with a fileset-like-structure.

A: Since Ant 1.8.0 there is a new resource collection - mappedresources that
can be used in place of the war task lib element.
So, the task might look like this (pretty much straight from the docs):
<war ... >
    <mappedresources>
        <restrict>
           <path refid="my.classpath"/>
           <type type="file"/>
        </restrict>
        <chainedmapper>
          <flattenmapper/>
          <globmapper from="*" to="WEB-INF/lib/*"/>
        </chainedmapper>
    </mappedresources>
</war>

This feature was added to resolve a long-standing feature request to make
the task flatten jars when deploying to WEB-INF/lib.
previous answer:
Although you can't easily convert a path to a fileset with vanilla Ant, you can go the other way.
So one option would be to define your jars in a fileset, and derive the path from it.
Something like this perhaps:
<fileset id="my.fileset" dir="${basedir}">
    <include name="folderA/subFolderA/1.0/A.jar"/>
    <include name="folderC/subFolderB/1.0/B.jar"/>
    <include name="folderF/subFolderZ/2.0/Z.jar"/>
    <include name="moreFolderF/subFolderZ/2.0/additionFile.jar"/>
    <include name="moreFolderF/subFolderZ/2.0/additionRuntimeFile.jar"/>
</fileset>

<path id="my.classpath">
    <fileset refid="my.fileset" />
</path>

<!-- javac stays the same -->

<war ...>
    <lib refid="my.fileset" />
</war>

Another possibility is to use the ant-contrib pathtofileset task.

A: Another solution, possibly 'not the best' will be to place required jar file in WEB-INF/lib, and then set the classpath from there.
<path id="compile.classpath">
    <fileset dir="${lib.dir}" includes="*.jar"/>
</path>

When its time to build the war, you need not worry about the <lib> at all, as jars are already placed in WEB-INF/lib folder.
<war destfile="${dist.dir}/${project.name}.war" webxml="${web.dir}/WEB-INF/web.xml">
        <fileset dir="${web.dir}"/>
        <classes dir="${build.dir}/classes"/>
    </war>


text:
Q: Pandas: New column from conditions and from another data frame I have two data frames, df1 and df2.
df1                df2
A   B              C   D   E
ad  df             ad  se  1
ad  se             xc  je  2
xc  je             ad  df  3
...                ...

I need to create a new column in df1 with the values contained in column E from df2. For this, I need to find the matching values between columns A and C, and from  B and D from df1 and df2 respectively.
where A == C & B == D
      XX = E

The result should be like this:
df1
A   B   XX
ad  df  3
ad  se  1
xc  je  2
...

This might be straightforward but I'm quite new to pandas and haven't really found a way to accomplish this.
Any advice is very welcome!

A: try this:
pd.merge(df1, df2.rename(columns={'C':'A', 'D':'B'}), on=['A', 'B'], how='left')

A: I think what you want can be accomplished with a simple call to the pd.merge or df.merge.
Minimal example
import pandas as pd

df1 = pd.DataFrame({'A': ['ad', 'ad', 'xc'], 'B': ['df', 'se', 'je']})
df2 = pd.DataFrame({'C': ['ad', 'xc', 'ad'], 'D': ['se', 'je', 'df'], 'E': [1, 2, 3]})

df1.merge(df2, left_on=['A', 'B'], right_on=['C', 'D'])

Output
    A   B   C   D  E
0  ad  df  ad  df  3
1  ad  se  ad  se  1
2  xc  je  xc  je  2

A: You can merge both the dataframes, based on the columns you mentioned.
>>> result = df1.merge(df2, left_on=['A', 'B'], right_on=['C', 'D'])
>>> result
    A   B   C   D   E
0   ad  df  ad  df  3
1   ad  se  ad  se  1
2   xc  je  xc  je  2

And drop the columns C and D.
result.drop(columns=['C', 'D'], inplace=True)

Else, a more elegant solution. Rename the columns from C and D to A and B, and you can just perform the merge.
>>> result = df1.merge(df2.rename(columns={'C': 'A', 'D': 'B'}))
>>> result
    A   B   E
0   ad  df  3
1   ad  se  1
2   xc  je  2

```py


text:
Q: ReferenceError: Can't find variable: onPlayerReady (When using callback) I am trying to use onPlayerReady() and onPlayerStateChange() as call backs for my YT Iframe Api wrapper, but I can't seem to reference an instance of my wrapper. How do I go about using the call back to call an instance of my wrapper?  I have gotten my code to work when my functions are outside of my wrapper, but I would love to have them inside the wrapper.
Error:
ReferenceError: Can't find variable: onPlayerReady
Player — player.self-7e1fbb555e29e354bc82162b755809f0b6435967f75b25c572d1953b57364c7c.js:12
onYouTubeIframeAPIReady — player.self-7e1fbb555e29e354bc82162b755809f0b6435967f75b25c572d1953b57364c7c.js:60
(anonymous function) — www-widgetapi.js:141:160
Global Code — www-widgetapi.js:141:215
jquery3.self-e200ee796ef24add7054280d843a80de75392557bb4248241e870fac0914c0c1.js:3842

CODE:
Helpers = window.Helpers || {};
Helpers.Google = Helpers.Google || {};
Helpers.Google.YT = Helpers.Google.YT || {};

Helpers.Google.YT = {

   Player: class Player {

    constructor(element = 'ytplayer', options = { playerVars: { controls: 1 },
                                                  height: '390',
                                                  width: '640',
                                                  videoId: 'novideoid',
                                                  events: {
                                                  'onReady': onPlayerReady,
                                                  'onStateChange': onPlayerStateChange
                                                }}, StubPlayerInstance = null ) {

      if (StubPlayerInstance == undefined) {
        this.player = new YT.Player(element, options);
      } else {
        this.player = StubPlayerInstance;
      }
    }

    loadVideoById($element) {
      var videoId = $element.data('video-id');
      var x = new String(videoId);
      this.player.loadVideoById(x);
    }

    init(modalId){
      const thatInstance = this;
      $(modalId).on('show.bs.modal', function(e) {
        thatInstance.loadVideoById($(e.relatedTarget));
      });
      return this.player;
    }

   onPlayerReady(event) {
     $('.open-popup').click(function() {
       event.target.playVideo();
     });
     $('.close-popup').click(function(e) {
       player.stopVideo();
     });
   }

   onPlayerStateChange(event) {
     if(event.data === 0) {
       $('.close.close-popup').click();
     }
    }
  }
}

var player;

function onYouTubeIframeAPIReady() {
  player = new Helpers.Google.YT.Player().init('#video-modal');
}

A: 'onReady': this.onPlayerReady.bind(this)
'onStateChange': this.onPlayerStateChange.bind(this)


text:
Q: Ios 7 compitible app crashes on launch. Why? I have just launched app,with IOS deplyment Target to  ios 6 and latest IOS SDK 8.1.
 Now App runs fine on ios 8 but i have some users with ios 7, saying app crashes on launch. I have checked all code ,nothing used which was deprecated. please guide me here.
I checked back in 2013 when IOS 7 launched, Many Apps was crashing, is this problem still persist?? How do i check on device with IOS 7, I did downgrade my phone's beta to IOS 7 but my app was working fine in my phone. Cant figure problem. Please some one help me.

A: I have some advice for you problem.

*

*You should use  https://try.crashlytics.com/ or https://mint.splunk.com/

*Please update Project | iOS | Deployment Target 8.1

*Please update Targets | Deployment Target 7.1

Question. when you compile your project . have you see any attention ?
good luck


text:
Q: where's the documentation for NodeJS's system module I see require("sys") used a lot, and I see that there is a CommonJS spec for a system module but some code that I see uses the module like so require("sys").error(e); and error does not appear to be listed in the CommonJS spec, so I'm wondering where I can find the documentation for the system module used by NodeJS, since I'm not seeing it in the NodeJS documentation.

A: Ah it looks like the module was renamed to be util so the documentation is at http://nodejs.org/docs/v0.4.2/api/all.html#util

Update: (merged from a subsequent answer from the same user)
The source is here: https://github.com/joyent/node/blob/master/lib/sys.js
But I'm hoping that there is actual documentation..


text:
Q: Check if uploaded image is CMYK in ActionScript 3.0 Is there any way to figure this out which user uploaded image in our flex project is RGB or CMYK?
Something like using byteArray and check the specific place of CMYK/RGB header on it...


text:
Q: Undefined function 'num2str' for input arguments of type 'double' I'm trying to use num2str in a load function as follows
route=3;
samples=1;
pct=100;

path('C:\')
load(['B2A_Sample_r',num2str(route),'_',num2str(pct),'%_',num2str(1000+samples)])

I also tried:
filename=char(['B2A_Sample_r',num2str(route),'_',num2str(pct),'%_',num2str(1000+samples)]);
load(filename,'-mat')

I'm having to shut down and reboot matlab every time I get this error.

A: You are clearing your path each time you run, so MATLAB can't find any files or functions, whether built-in or not (including num2str). Each time it tries, it only looks in C:\ and then gives up. Try this:
route=3;
samples=1;
pct=100;
filename=char(['B2A_Sample_r',num2str(route),'_',num2str(pct),'%_',num2str(1000+samples)]);
directory = 'C:\';

fullfilename = fullfile(directory,filename);

load(fullfilename);


text:
Q: SharePoint and SAML: Is there any guard against a replay attacks? SharePoint uses SAML 1.1 as a protocol for federated authentication. A user will log in to a trusted identity provider and a SAML token is posted to the SharePoint site as a means of logging in to SharePoint.
I was surprised to find that the lifetime of the SAML token ties directly to the user's session. By default this seems to be 10 hours, which seems generous.
If I issue a SAML token to SharePoint what guard is there against replay attacks? It seems this token post is replayable for the lifetime of the user session. I would have expected the token lifetime to be long enough to authenticate. Is there something I am missing or is this a security hole?

A: The session lifetime in SharePoint will not be equals to the SAML token lifetime, but to the SAML Token ValidTo property (i.e. an absolute datetime), so the replay will work till that absolute time.

But there is more than that, SharePoint also relies on an internal property (defaults to 10 minutes) called LogonTokenCacheExpirationWindow. In my opinion, it brings more confusion than what value, but it's there and you have to understand that the validity of the session will depend on that
In pseudo code this is what happens inside SharePoint
SessionToken Lifetime = SAML Token Lifetime (by default)
if (SessionToken Lifetime - LogonTokenCacheExpirationWindow < DateTime.UtcNow)
    Logout()

Here you have an illustration of that with LogonTokenExpirationWindow = 40 mins and SAML Token Lifetime 1hr.

The LogonTokenCacheExpirationWindow can be changed like this:
$sts = Get-SPSecurityTokenServiceConfig
$sts.LogonTokenCacheExpirationWindow = (New-TimeSpan -minutes 1)
$sts.Update()

The SAML token lifetime (in case you use ADFS) can be changed like this:
Set-ADFSRelyingPartyTrust -TargetName "My SP2010" -TokenLifetime 5

Finally, it is worth noting that SharePoint will issue persistent cookies by default. So when you close the browser and open it again, it will use that persistent cookie. You can change that by setting
$sts = Get-SPSecurityTokenServiceConfig
$sts.UseSessionCookies = $true
$sts.Update()
iisreset


text:
Q: Strange output of php decorator pattern I have implemented a basic snipe of code based in decorator pattern.
Decorator class:
abstract class HTMLDecorator {

    /** @var \ArrayObject */
    protected $notes;

    public function format(){
        $html = '';

        foreach ($this->getNodes() as $node)
            $html .= "<p>{$node}</p>";

        return $html;
    }
}

This is the base class:
class HTML extends HTMLDecorator{

    public function __construct(){
        $this->nodes = new \ArrayObject();
    }

    public function getNodes(){
        return $this->nodes;
    }
}

Now, these two classes add nodes to the html array.
Block:
class BlockHtml extends HTMLDecorator{

    protected $html;

    public function __construct(HTMLDecorator $html){
        $this->html = $html;
    }

    public function getNodes()
    {
        $this->html->getNodes()->append('Block html');
        return $this->html->getNodes();
    }

}

Image:
class ImageHtml extends HTMLDecorator{

    protected $html;

    public function __construct(HTMLDecorator $html){
        $this->html = $html;
    }

    public function getNodes()
    {
        $this->html->getNodes()->append('Image html');
        return $this->html->getNodes();
    }

}

Finally, I have tested it as doing:
$html = new HTML()
$html = BlockHTML($html);
$html = ImageHTML($html);
echo $html->format();

The result is:
Block html
Image html
Block html

Why does code print "Block html" twice?

A: Calling $html = ImageHTML($html); using the result obtained from $html = BlockHTML($html); might causing the problem. Can you try to assign the returned value to different variable and assemble it at the end.


text:
Q: a simple tutorial for implementing twitter in my iphone application i searched alot also looked on stack over flow , so please don't make this duplicate question,
I am not able to find a simple and complete tutiorial for implementing the twitter for iphone ,
please help

A: I have used google and found some:

*

*http://www.iphonedevx.com/?p=1303

*http://www.icodeblog.com/2009/07/09/integrating-twitter-into-your-applications/

*https://github.com/doubleencore/DETweetComposeViewController
hope this works for you !


text:
Q: HttpPost doesn't work in C#, but works correctly in Android I'm doing a HttpPost to a rest service to Revoke a license. On Android, the request works perfectly. But when doing the post in c#, I get the response

"No action was found on the controller that matches the request"

In Android:
@Override
protected String doInBackground(String... params)
{
        String request = serverUrl + "api/Public/RemoveInstall?DeviceID="+deviceId+"&UserID="+m_userID;
        try {
            if(!isNetworkAvailable())
            {
                return "no_accesToken";
            }
            else
            {
                URL url = new URL(request);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setDoOutput(false);
                conn.setInstanceFollowRedirects(false);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("charset", "utf-8");
                conn.setConnectTimeout(1500);
                conn.setUseCaches(false);
                conn.connect();

                ...
}

The code above works perfectly, but in c# it won't work:
public async Task<bool> RevokeLicenseAsync(string userId)
{
        if (!IsInternetConnected())
        {
            errorMsg = "No internet connection";
            return false;
        }

        string deviceId = GetDeviceID();

        var postData = new List<KeyValuePair<string, string>>();
        postData.Add(new KeyValuePair<string, string>("DeviceID", deviceId));
        postData.Add(new KeyValuePair<string, string>("UserID", userId));

        //the header arguments "ContentType" and "ContentLength are filled in automatically"
        var formContent = new FormUrlEncodedContent(postData);

        if (!String.IsNullOrEmpty(token))
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(serverUrl);

                using (var response = await httpClient.PostAsync("api/Public/RemoveInstall",formContent))
                {

A: Can you change like following
public async Task<bool> RevokeLicenseAsync([FromBody]string userId),

if you doing post request with one type parameter, you have to specify FromBody or FormUri

A: In the android request you post the parameters in the url but in the second one you post it in the body.
If the first one works then try do the same for the second one.
var requestUri = string.Format("api/Public/RemoveInstall?DeviceID={0}&UserID={1}", deviceId, userId);
var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
using (var httpClient = new HttpClient()) {
    httpClient.BaseAddress = new Uri(serverUrl);
    using (var response = await httpClient.SendAsync(request)) {
        //...other code


text:
Q: When will it be considered an OVERKILL when making a composite primary key? Recently, I stumbled upon this question when looking through my database notes.
In the case of an annual examination (A Levels, O Levels) where students who did not attain their desired marks are allowed for a re-sit in the following years,
suppose there was a database designed for the school to track that has the following attributes
Student ID, Exam module, Exam Date, Exam Results

Question provided by the book (not my personal question): what would be some appropriate primary keys?[5]
Now, I know that several primary key should not be used:

*

*Purely Student ID

*(Student ID + Exam Module)
And I also know that perhaps

*

*Artificial Primary Key - extending a 5th column that auto-increments

*(Student ID + Exam Module + Exam Date)
could be used as a primary key
My question comes from making a composite primary key from all attributes (Student ID + Exam Module + Exam Date + Exam Results). A part of me thinks it will work as a composite primary key but it does not make sense to provide every single table with a composite primary key consisting of all columns.

A: From your description of the question, the following tuple of columns should be unique throughout the table: (StudentID, ExamModule, ExamDate), because a student may take the same exam on different dates (actually: different years). The result of the exam should not be part of this unique column tuple: this prevents a student to two results for the same exam.
Whether you decide to make this tuple of columns the primary key of your table or use some kind of serial column as primary key is mostly a matter of taste. If you go for a serial key, you need to put a composite unique constraint on the three above columns anyway.

A: This is not necessarily along the line of the OP's initial question:

Question: what would be some appropriate primary keys?

but..(in hind site) I would have an IDENTITY field as a primary key.
And have the StudentID as just an Index (non unique) and as an alternate Key.


text:
Q: How can I create a virtual output in PulseAudio? I need to create a virtual output in PulseAudio so as to be able to capture and stream audio from a specific source.
I know that it's possible to re-route a specific application's output to a given output device like so, using pavucontrol:

I'm looking to add another virtual output to the "Output Devices":

Is this possible, and if so, how can I do it?

A: Besides creating the sink, most applications filter out monitor sources. To be able to pick the source directly for example in Google Meet, the module-remap-source helps.
# create sink
pactl load-module module-null-sink sink_name=virtmic \
    sink_properties=device.description=Virtual_Microphone_Sink
# remap the monitor to a new source
pactl load-module module-remap-source \
    master=virtmic.monitor source_name=virtmic \
    source_properties=device.description=Virtual_Microphone

(found this from https://aweirdimagination.net/2020/07/19/virtual-microphone-using-gstreamer-and-pulseaudio/)
Another possibility is to create a file ~/.config/pulse/default.pa
with content:
.include /etc/pulse/default.pa

load-module module-null-sink sink_name=virtmic sink_properties=device.description=Virtual_Microphone_Sink
load-module module-remap-source master=virtmic.monitor source_name=virtmic source_properties=device.description=Virtual_Microphone

run pulseaudio -k to reload the configuration
You can use pavucontrol to route the audio from any application (like Spotify) to the virtual microphone sink.

A: I never could get snd_aloop to work on my systems. Furthermore using ffmpeg -f pulse -i alsa_output.pci-0000_00_1f.3.analog-stereo.monitor etc. caused there to be a 1-2 second lag in the system audio recording. The answer by mxc helped me to find my solution, but I wanted to add a little bit of information.
I first needed to set my Pulse Monitor of Built-in Audio to default. Then I ran the commands listed above. I wanted this to be the default on my profile every time so I created ~/.config/pulse/default.pa and added the following lines:
.include /etc/pulse/default.pa

set-default-source alsa_output.pci-0000_00_1f.3.analog-stereo.monitor
load-module module-null-sink sink_name=MySink
update-sink-proplist MySink device.description=MySink
load-module module-loopback sink=MySink

The first line includes the system-wide PulseAudio settings. Then the last four lines are prioritized for the user over any system settings. Of course any of the last four lines can be run in the terminal when preceded by pacmd.
To get the name of your Pulse Monitor of Built-in Audio device run:
pacmd list-sources | awk '/index:/ {print $0}; /name:/ {print $0}; /device\.description/ {print $0}'

A: You can add a sink with
pacmd load-module module-null-sink sink_name=MySink
pacmd update-sink-proplist MySink device.description=MySink

You can add a loopback device with the command
pacmd load-module module-loopback sink=MySink

A: sudo modprobe snd_aloop

Adds a loopback device to ALSA, which appears in the PulseAudio Volume Control. Redirect your stream there, and presto!
Not sure how to add multiple loopback devices.

A: A little complement to @mxc's answer, as he said you can use the module-null-sink as a virtual output with:
    pacmd load-module module-null-sink sink_name=MySink

This creates a new sink ("virtual output") that you can use for your application. For every sink you create, pulseaudio will also create a monitor source, so in addition to your MySink output device, you will have a MySink.monitor input device that you can use to capture what is sent to your virtual output.
This way it is easy to capture, restream or record the audio an application outputs.
This is a pure Pulseaudio solution and doesn't require Alsa, so it will also work with a different backend than Alsa for Pulseaudio.


text:
Q: Passing sanitized input with function does not work I've been having a problem the past few days where I've narrowed the problem as shown below.  The passing of the parameters works fine if I don't use it with the custom distance function.  Can anyone tell me what I'm doing wrong?  As of now, I'm just sanitizing the field manually and hard coding it into the query.
WORKS (returns correct results):
$sth = $db->prepare("SELECT * FROM providers WHERE distance('42.8','-73.9',lat,lon)<25");
$sth->execute();

DOES NOT WORK (returns all providers):
$sth = $db->prepare("SELECT * FROM providers WHERE distance('42.8','-73.9',lat,lon)<:radius");
$sth->execute(array(":radius" =>25));

A: I'm not real familiar with PDO, but possibly it is because you are passing an int and the statement treats values as a string by default.  See the manual page: http://php.net/manual/en/pdostatement.execute.php and look under input_parameters for more.  You could always try using bind_param() to get your data into the correct type before executing your statement.

A: try this code:
I'm a little new to PDO myself, but I found this to work for me:
$radius = 25;
$sth = $db->prepare("SELECT * FROM providers WHERE distance('42.8','-73.9',lat,lon)<:radius");
$query_params = array(
        ':radius' => $radius
    );
$sth = $db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)); // forgot

$sth -> execute($query_params);


text:
Q: How can you take torque about an accelerating point that isn't the center of mass? Before I ask this question, let me describe the set-up. You have a simple pendulum attached to the ceiling. At the bottom of the pendulum there is a sphere. The sphere rotates counterclockwise when going to the right, and then rotates clockwise while going to the left.

The question was to find what direction the net torque is on the ball  with respect to to point of attachment between the sphere and the ball when the pendulum is at its max rightward displacement. Now, this is what confused me. When I learned torque, I learned that measuring torque is only meaningful (ex. you can apply $τ = Iα$ and $τ = \mathrm dL/\mathrm dt$) when you measure torque about the center of mass or a point that is fixed (not moving or moving at constant velocity).
The point of attachment is essentially in free-fall at the max rightward displacement (and is hence accelerating) and is not the center-of-mass of the ball, so from what I learned, this is an "invalid" point of taking torque (ex. you can't make assumptions on the motion of the ball from taking torque about this point). Instead of taking torque about the point of attachment, I took torque about the center point when the ball was at its max rightward displacement. From this perspective, the ball rotates from a counterclockwise direction to a clockwise direction. Therefore, from the point of the center-of-mass of the ball, the torque must be clockwise.
That was my answer, but as I said the question asked what was the torque relative to the point of attachment. The answer was

At the sphere's maximum rightward displacement, the gravitational force (taken to act at the
  center of the sphere) exerts a clockwise torque about the point of attachment to the string.

I understand everything except how they took torque about the point of attachment. From my understanding, taking torque about these "non-valid" origins can lead to wrong conclusions. For example, look at this diagram of a block in space. If you take torque about point a, one will find torque to be zero and hence conclude that the object is not spinning. However, taking torque about the center of mass reveals there is a net torque and hence a change in rotation.
So, my question is, am I wrong in thinking that taking the torque about the point-of-attachment is invalid?
Credits of first picture and problem goes to AP College Board (this is a public problem you can find online)
Credits of second picture to another physics exchange user (neverneve)

A: You have two choices if you want to consider a point that is not the CoM.

*

*consider the point fixed in an inertial frame.

Under this method, you are doing an instantaneous calculation.  The object will move away from that point, but the point itself is not accelerating.  The main problem is that if the CoM of the object is not in line with the point, its acceleration will change the angular momentum without necessarily changing the angular velocity.
If you consider a rod in freefall, torque about the right end would appear to be positive from the force of gravity.  But this torque instead of rotating the rod is accelerating it downward.  The angular momentum of $L = mvd$ is increasing as $v$ increases.  Non-zero torque, increasing angular momentum (but not rotation).

*

*consider the point moving with the object.

Since the point considered is no longer at rest in an inertial frame, fictitious forces arise.  These forces are in opposite direction of the acceleration of the frame, applied through the CoM.  In this case when we examine the rod from the right end, a torque appears from the pull of gravity.  But a counter-torque appears from the non-inertial frame.  These two torques cancel out exactly, and the rod does not rotate (as expected).

A: Here is the full concept. You can find torque about any point.
Problem is you cannot apply $\tau = I \alpha$ about any point.
To apply $\tau = I \alpha$, we need to make sure that the point is inertial. That leaves us with three options (not two)

*

*Choose fixed axis. It is an inertial point. So we don't face any problem.

*Choose centre of mass. If it is not inertial, torque of pseudo force has to be considered. Fortunately, pseudo force acts at CoM. So its torque around CoM is always zero.

*Choose any arbitrary point. But make sure that you consider torque of pseudo force while while applying $\tau = I \alpha$.

Now try the question again!

A: At the instant of maximum displacement, the point of attachment is instantaneously at rest. That point in space can be taken as a point of reference for the rate of change of the angular momentum of the sphere caused by gravity. This would include only the angular momentum associated with the motion of the center of mass.


text:
Q: Mapping a model into a dto and 'include' only the key of child element I have the following Project model:
public class Project
{
    [Key]
    public int      ProjectID       { get; set; }
    public string   Name            { get; set; }
    public string   Description     { get; set; }
    public virtual  ICollection<Screenshot> Screenshots { get; set; }
}

And I have the following Screenshot model:
public class Screenshot
{
    [Key]
    public int    ScreenshotID { get; set; }
    public string ScreenshotName { get; set; }
    public byte[] ScreenshotContent { get; set; }
    public string ScreenshotContentType { get; set; }
}

As you can see, each project have some screenshots attached. In the following function, I would like to retrieve some projects and only the ID of the corresponding screenshots.
public SearchResultDTO<ProjectDTO> GetProjects(SearchParametersProjectDTO dto)
{
    ...
    var resultDTO = new SearchResultDTO<ProjectDTO>
    {
        Entities = Mapper.Map<IEnumerable<Project>, IEnumerable<ProjectDTO>>(projects.ToList()),
        TotalItems = projects.Count()
    };
    return resultDTO;
}

Here is the ProjectDTO:
[DataContract]
public class ProjectDTO : BaseDTO<ProjectDTO, Project>
{
    [DataMember]
    public int ProjectID { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Description { get; set; }

    [DataMember]
    public IEnumerable<int> ScreenshotID { get; set; }

So I don't know how to map ScreenshotID in my DTO.
Any help is greatly appreciated.
Thanks.

A: Create a mapping between Screenshot and int:
Mapper
    .CreateMap<Screenshot, int>()
    .ConvertUsing(s => s.ScreenshotID);

and inside the mapping between Project and ProjectDTO use it:
Mapper
    .CreateMap<Project, ProjectDTO>()
    .ForMember(
        dest => dest.ScreenshotID,
        opt => opt.MapFrom(src => src.Screenshots)
    );

And when you want to map:
var project = new Project
{
    Screenshots = new[]
    {
        new Screenshot { ScreenshotID = 1 },
        new Screenshot { ScreenshotID = 2 },
        new Screenshot { ScreenshotID = 3 },
    }
};

var projectDto = Mapper.Map<Project, ProjectDTO>(project);

// at this stage the projectDto.ScreenshotID collection will contain
// the necessary information